Concept:
- mybatis is a persistence framework, a top-level project under apache
- Let the program focus on sql, through the mapping method provided by mybatis, free and flexible generation of SQL statements needed.
- The parameters in the prepareStatement can be automatically input mapped, and the query result set can be flexibly mapped to java objects. (output mapping)
Problems encountered:
①Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Cause: The latest mysql-connector-java-8.0.11-.jar MySQL driver package is used. The `com.mysql.jdbc.Driver'class in the new driver package is outdated. It is automatically registered through SPI and no longer needs to load the driver class manually.
②java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone.
Modification: value="jdbc: mysql://localhost:3306/test?serverTimezone=GMT%2B8"/
(3) When the content in the data table is of Date type, the query statement will report an error. I don't know why. If the big man knows, please tell him.
Architecture
Import the required jar package:
Query data according to Id
- log4j.properties
log4j.rootLogger = DEBUG,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
- User.xml
<?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"> <mapper namespace="test"> <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.Employee">//parameterType input type, resultType output result type select id,username,sex,address from users where id=#{id};//#{} is a placeholder </select> </mapper>
- SqlMapConfig.xml
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment> </environments> <mappers> <mapper resource="sqlmap/User.xml"/> </mappers> </configuration>
- Employee.java
package cn.itcast.mybatis.po; import java.sql.Date; public class Employee { private int id; private String username; private String sex; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Employee [id=" + id + ", username=" + username + ", sex=" + sex + ", address=" + address + "]"; } }
- MybatisFirst.java
package sqlmap; import java.io.IOException; import java.io.InputStream; 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 cn.itcast.mybatis.po.Employee; public class MybatisFirst { @Test public void findUserByIdTest() throws IOException{ String resource="SqlMapConfig.xml";//configuration file InputStream inputStream= Resources.getResourceAsStream(resource);//Get the configuration file stream SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);//Create a session factory and pass in configuration file information SqlSession sqlSession =sqlSessionFactory.openSession();//Get sqlsession from the factory Employee employee =sqlSession.selectOne("test.findUserById",1);//It's selectOne that queries a piece of data System.out.println(employee); sqlSession.close(); //Closing session } }
Fuzzy query data by name
- SqlMapConfig.xml
<select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.Employee"> select id,username,sex,address from users where username like '%${value}%';//${} may cause sql injection, just a splice, without any change </select>
- Test file
@Test public void findUserByNameTest() throws IOException{ String resource="SqlMapConfig.xml"; InputStream inputStream= Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession =sqlSessionFactory.openSession(); java.util.List<Employee> list= sqlSession.selectList("test.findUserByName", "zhao");//selectList Queries Multiple Data System.out.println(list); sqlSession.close(); }
Adding data to the database
- SqlMapConfig.xml
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.Employee"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> select LAST_INSERT_ID(); //Query Self-Increasing Primary Key Value </selectKey> insert into users(id,username,sex,address)value(#{id},#{username},#{sex},#{address}); </insert>
- Test file
@Test public void insertUserTest() throws IOException{ String resource="SqlMapConfig.xml"; InputStream inputStream= Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession =sqlSessionFactory.openSession(); Employee employee= new Employee(); employee.setId(10); employee.setUsername("wu"); employee.setSex("nv"); employee.setAddress("henan"); sqlSession.insert("test.insertUser",employee); sqlSession.commit(); System.out.println(employee.getId());//Output Self-Increasing Primary Key Value sqlSession.close(); }
Delete files from the database
- SqlMapConfig.xml
<delete id="deleteUser" parameterType="java.lang.Integer"> delete from users where id=#{id}; </delete>
- Test file
@Test public void deleteUserTest() throws IOException{ String resource="SqlMapConfig.xml"; InputStream inputStream= Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession =sqlSessionFactory.openSession(); sqlSession.delete("test.deleteUser",12); sqlSession.commit(); sqlSession.close(); }
Update the data in the database
- SqlMapConfig.xml
<update id="updateUser" parameterType="cn.itcast.mybatis.po.Employee"> update users set username=#{username},sex=#{sex},address=#{address} where id=#{id}; </update>
- Test file
@Test public void updateUserTest() throws IOException{ String resource="SqlMapConfig.xml"; InputStream inputStream= Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession =sqlSessionFactory.openSession(); Employee employee= new Employee(); employee.setId(13); employee.setUsername("sheng"); employee.setSex("nv"); employee.setAddress("diqiu"); sqlSession.update("test.updateUser",employee); sqlSession.commit(); sqlSession.close(); }