Idea: build environment –> import Mybatis– > code –> test
1.1. Setting up the environment
Build a database
create databases if not exists `mybatis`;
use `mybatis`;
create table if not exists `user`(
`id` int(20) not null,
`name` varchar(30) default null,
`pwd` varchar(30) default null,
primary key(`id`)
)engine=innodb default charset=utf8;
Insert data
Insert into ` user ` (` id `, ` name `, ` PWD `) values (1, 'the Monkey King', '123456'), (2, 'pig eight quit', '111222'), (3, 'tang's monk', '789456');
1. Create a normal Maven project 2. Delete SRC directory 3. Import Maven dependencies
<dependencies> <! -- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.46 < / version > < / dependency > <! --mybatis-- -> <dependency dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <! -- jUnit --> <groupId> jUnit </groupId> <artifactId> jUnit </artifactId> <version>4.12</version> </dependency> </dependencies> <! Configure resources in build; > <build> <resources> <resource> <directory> SRC /main/ Java </directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
1.2. Create a module
-
Write the core configuration file for MyBaris
<? The 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/mybatis? useSSL=true& useUnicode=true& characterEncoding=utf-8& serverTimezone=Asia/Shanghai"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/jialidun/dao/UserMapper/xml"/> </mappers> </configuration>
-
Write the MyBatis tool class
package com.jialidun.utils; //sqlSessionFactory--->sqlSession public class MybatisUtils{ private static SqlSessionFactory sqlSessionFactory; Static {try{// SqlSessionFactory object String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }catch(IOException e){ e.printStackTrace(); }} // Now that we have the SQLSessionFactory, as the name implies, we can get an instance of the SQLSession from it. // The SQLSession provides all the methods needed to execute SQL commands in the database. public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); }}
1.3. Write code
-
Entity class
package com.jialidun.pojo; @Data public class User{ private int id; private String name; private String pwd; }
-
The Dao interface
package com.jialidun.dao; Public interface userDAO {list_user_list <User> getUserList(); User getUserById(int id); //insert User int addUser(User User); // updateUser int updateUser(User User); // deleteUser int deleteUser(int id); }
-
The interface implementation class is transformed from the original UserDaoImpl to a Mapper configuration file, userMapper.xml
<? The 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 = Bound a corresponding DAO /Mapper interface --> < Mapper Namespace =" com.jialidun.dao.userdao "> <! ResultType ="com.jialidun.pojo.User"> select * from mybatis. User </select> from mybatis <select id="getUserById" parameterType="int" resultType="com.jialidun.pojo.User"> select * from mybatis.user where id = #{id} </select> <! - properties in the object, > <insert id="addUser" parameterType="com.jialidun.pojo.User"> insert into mybatis. User (id,name, PWD) values(#{id},#{name},#{pwd}); </insert> <update id="updateUser" parameterType="com.jialidun.pojo.User"> update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}; </update> <delete id="deleteUser" parameterType="int"> delete from mybatis.user where id=#{id}; </delete> </mapper>
1.4, tests,
Note: org.apache.ibatis.binding.BindingException:Type interface com.jialidun.dao.UserDao is not know to the MapperRegistry.
package com.jialidun.dao; Public class UserDaotest {@test public void Test (){ Get the SqlSession objects SqlSession SqlSession = MybatisUtils. GetSqlSession (); try{ UserDao userDao= sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); 2: / / way / / the List < User > userList. = sqlSession selectList (" com. Jialidun. Dao. UserDao. GetUserList "); for(User user:userList){ System.out.println(user); } }catch(Exception e){ e.printStackTrace(); }finally{// Close SQLSession SQLSession.close (); } } @Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); User user = mapper.getUserById(1); System.out,println(user); sqlSession.close(); } @Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); Int num = map.addUser (4, num, addUser); int num = addUser(4, num, addUser); If (num>0){system.out.println (" User added successfully! "); ); } // commit the transaction SQLSession.com MIT (); sqlSession.close(); } @Test public void updateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); Map. updateUser(new User(4," 666666","666666")); // commit the transaction SQLSession.com MIT (); sqlSession.close(); } @Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); mapper.deleteUser(4); // commit the transaction SQLSession.com MIT (); sqlSession.close(); }}
Possible problems encountered: 1. Configuration file not registered 2. Binding interface error 3. Incorrect method name 4. Incorrect return type 5.Maven export resource problem
2. CRUD operation of Mtbatis
2.1, the namespace
Package names in namespace should be the same as package names in the DAO/Mapper interface!
2.2, the select
Select, query statement
- Id: is the name of the method in the corresponding namespace;
- ResultType: The return value from SQL statement execution!
-
ParameterType: Parameter Type 1. Write the interface
Select * from User where userById (int id);
2. Write the corresponding SQL statement in the Mapper
<select id="getUserById" parameterType="int" resultType="com.jialidun.pojo.User"> select * from mybatis.user where id = #{id} </select>
3. The test
@Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); User user = mapper.getUserById(1); System.out,println(user); sqlSession.close(); }
2.3, the Insert
1. Write interfaces
//insert 一个用户 int addUser(User user);
2. Write the corresponding mapper worth SQL
<! - properties in the object, > <insert id="addUser" parameterType="com.jialidun.pojo.User"> insert into mybatis. User (id,name, PWD) values(#{id},#{name},#{pwd}); </insert>
3. The test
@Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); Int num = map.addUser (4, num, addUser); int num = addUser(4, num, addUser); If (num>0){system.out.println (" User added successfully! "); ); } // commit the transaction SQLSession.com MIT (); sqlSession.close(); }
2.4, the update
1. Write interfaces
// updateUser int updateUser(User User);
2. Write the corresponding mapper worth SQL
<update id="updateUser" parameterType="com.jialidun.pojo.User"> update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}; </update>
3. The test
@Test public void updateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); Map. updateUser(new User(4," 666666","666666")); // commit the transaction SQLSession.com MIT (); sqlSession.close(); }
2.5, delete
1. Write interfaces
// deleteUser int deleteUser(int id);
2. Write the corresponding mapper worth SQL
<delete id="deleteUser" parameterType="int"> delete from mybatis.user where id=#{id}; </delete>
3. The test
@Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserDao.class); mapper.deleteUser(4); // commit the transaction SQLSession.com MIT (); sqlSession.close(); }
Note:
- To add, delete or change a transaction needs to be committed!
3. Analyze errors
- Don’t match labels wrong
- Resource binding mapper, need to use the path!
- Program configuration files must conform to the specification!
- NullPointException, not registered with resource!
- There are no export issues with Maveb resources!