Mybatis from beginner to proficient (I)
1、 Frame principle:
2、 Getting Started
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency>
#Initialize definition log level log4j.rootLogger=DEBUG,Console #Output to console log4j.appender. Console=org.apache.log4j. ConsoleAppender log4j.appender. Console.layout=org.apache.log4j. PatternLayout log4j.appender. Console.layout. ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.org.apache=INFO
<? xml version="1.0" encoding="UTF-8" ?> <! DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" " http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <properties resource="jdbc.properties" /> <settings> <!-- Set automatic hump naming conversion --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- After integration with spring, the environment configuration will be abolished --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <!-- Load mapping file --> <mapper resource="com/lcry/mybatis/dao/EmployeeMapper.xml"/> </mappers> </configuration>
driver=com.mysql.jdbc. Driver url=jdbc: mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf -8 username=root password=123456
package com.lcry.mybatis.bean; public class Employee { private Integer id ; private String lastname; // There is a pit here private String email; private String gander; // There is a pit here public Integer getid() { return id; } public void setId(Integer id) { this.id = id; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGander() { return gander; } public void setGander(String gander) { this.gander = gander; } @Override public String toString() { return "Employee{" + "id=" + id + ", lastname='" + lastname + '\'' + ", email='" + email + '\'' + ", gander='" + gander + '\'' + '}'; } }
package com.lcry.mybatis.dao; import com.lcry.mybatis.bean. Employee; public interface EmployeeDao { Employee getEmp(Integer id); void insertemp(Employee employee); boolean updateemp(Employee employee); Integer deleteemp(Integer id); }
<? xml version="1.0" encoding="UTF-8" ?> <! DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" " http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <!-- Namespace, which can be customized. If an interface is bound, it must be consistent with the interface name --> <!-- ID is a unique identifier --> <mapper namespace="com.lcry.mybatis.dao.EmployeeDao"> <select id="getEmp" resultType="com.lcry.mybatis.bean.Employee"> select * from tbl_employee where id = #{id} </select> <insert id="insertemp" useGeneratedKeys="true" keyProperty="id"> insert into tbl_employee VALUES(null,#{lastname},#{gander},#{email}) </insert> <update id="updateemp"> /*Solve the pit last_name here*/ update tbl_employee set last_name = #{lastname} ,gender=#{gander},email=#{email} where id=#{id} </update> <delete id="deleteemp"> DELETE FROM tbl_employee WHERE id =#{id} </delete> </mapper>
package com.lcry.mybatis.test; import com.lcry.mybatis.bean. Employee; import com.lcry.mybatis.dao. EmployeeDao; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session. SqlSession; import org.apache.ibatis.session. SqlSessionFactory; import org.apache.ibatis.session. SqlSessionFactoryBuilder; import org.junit. Test; import java.io.IOException; import java.io.InputStream; public class MyBatisTest { //Get configuration and create sqlSessionFactory factory public static SqlSessionFactory getsqlsession() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); return sqlSessionFactory; } @Test public void test01() throws IOException { SqlSession sqlSession = getsqlsession().openSession(); try { //Query Method Employee employee = sqlSession.selectOne("com.lcry.mybatis.dao.EmployeeDao.getEmp", 10); System.out.println(employee); } finally { sqlSession.close(); } } @Test public void test02() throws IOException { SqlSession sqlSession = getsqlsession().openSession(true); try { EmployeeDao employee = sqlSession.getMapper(EmployeeDao.class); //Query Method Employee emp = employee.getEmp(10); System.out.println(emp.getid()); //Insertion method Employee employee1 = new Employee(); employee1.setLastname("lcry"); employee1.setEmail("1@qq.com"); employee1.setGander("1"); employee.insertemp(employee1); System.out.println(employee1.toString()); //Update method boolean b = employee.updateemp(employee1); System.out.println(b + employee1.toString()); //Delete Method Integer rows = employee.deleteemp(13); System.out.println(rows); } finally { sqlSession.close(); } } }
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for tbl_employee -- ---------------------------- DROP TABLE IF EXISTS `tbl_employee`; CREATE TABLE `tbl_employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `last_name` varchar(255) DEFAULT NULL, `gender` char(1) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tbl_employee -- ---------------------------- INSERT INTO `tbl_employee` VALUES ('10', 'lcry', '1', '1@qq.com'); INSERT INTO `tbl_employee` VALUES ('11', 'lcry', '1', '1@qq.com'); INSERT INTO `tbl_employee` VALUES ('12', 'lcry', '1', '1@qq.com'); INSERT INTO `tbl_employee` VALUES ('14', 'lcry', '1', '1@qq.com');