A, mybatis environment to build step
Step 1: Create maven project
Step Two: Import coordinate
third step: write the necessary code for (the entity class and persistence layer interface)
Step Four: Write SqlMapConfig.xml
Step five: Write mapping configuration file
Step Six: Writing Test class
Second, write 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="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!- <>by mappers<->Specifies the location mapping configuration file mapper resource="com/jzq/dao/UserDao.xml"/> </mappers> </configuration>
Third, adding CRUD methods in the persistence layer (DAO) interface
Package com.jzq.dao; Import com.jzq.domain.User; Import java.util.List; / ** * @author JZQ * @Create 2019-08-24 PM 1:39 * / public interface UserDao { List < the User> findAll (); / ** * preservation method * @param the User * / void saveUser (the User the User); / ** * modify method * @param the User * / void updateUser (the User the User); / ** * delete method * @param userId * / Void deleteUser (Integer userId); / ** * Looking for a specified user id * @param id * @return * / the User FindUser (Integer id); / ** * Fuzzy query * / List <the User> findByLikeName (String username) ; / ** * total number of queries the user * / int findTotal (); }
Fourth, the configuration in the user's mapping configuration file (Mapper) in
<?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="com.jzq.dao.UserDao"> <select id="findAll" resultType="com.jzq.domain.User"> SELECT * from user </select> <!-- 保存用户 --> <insert id="saveUser" parameterType="com.jzq.domain.User " after insertion configuration, acquiring insert data id<-!> --> <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER"> SELECT last_insert_id(); </selectKey> INSERT INTO user(username,birthday,sex,address)VALUE (#{username},#{birthday},#{sex},#{address}) </insert> <!-- 更新用户 --> <update id="updateUser" parameterType="com.jzq.domain.User"> UPDATE user set username=#{username},sex=#{sex} WHERE id=#{id}; </update> <!--Delete user -> < the Delete id = "deleteUser" parameterType = "Integer" > DELETE the FROM the User the WHERE id = # {uId} </ the Delete > <-! Query specifies the user id -> < the SELECT id = "FindUser" the parameterType = "Integer" the resultType = "com.jzq.domain.User" > the SELECT * from the WHERE ID User UID = # {} </ SELECT > <-! fuzzy search based on the name -> < SELECT ID = "findByLikeName" parameterType="String" resultType="com.jzq.domain.User"> SELECT * from user WHERE username like #{name} </select> <!-- 查询用户的总记录数 --> <select id="findTotal" resultType="int"> SELECT COUNT(id) from user; </select> </mapper>
Fifth, test class test CRUD methods
package com.jzq.test; import com.jzq.dao.UserDao; import com.jzq.domain.User; 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.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.Date; import java.util.List; /** * @author jzq * @Create 2019-08-24 PM 2:44 * the CRUD operations * / public class MyBatisTest { Private the InputStream in; Private the SqlSession SQLSESSION; Private a SqlSessionFactory Factory; Private UserDao userDao; @Before // performed prior to performing the test method public void the init () throws Exception { // read the configuration file to generate an input stream of bytes in Resources.getResourceAsStream = ( "the SqlMapConfig.xml" ); // Get SqlSessionFactory Factory = new new the SqlSessionFactoryBuilder () Build (in).; // Get the object SQLSession = SQLSESSION factory.openSession (); // Get the proxy object dao userDao = sqlSession.getMapper (UserDao. class ); } @After // performed after the test method of performing public void the destroy () throws Exception { // release resources SQLSESSION .commit (); sqlSession.close (); in.close (); } / ** * test to Find * * @throws Exception * / @Test public void testFindAll () throws Exception { // execute the query in all methods List <the User> Users = userDao.findAll (); for (the User User: Users) { System.out.println (User); } // release resources sqlSession.close (); in. Close (); } / ** * save operation test * / @Test public void testSave () throws Exception { the User User = new new the User (); user.setUsername ( "mybaitis_save" ); user.setBirthday ( new new a Date ()) ; user.setSex ("Male" );); User.setAddress ( "District Beijing non-station" ); // execute preservation method userDAO.saveUser (User); sqlSession.commit (); } / ** * save operation test * / @Test public void testFindInsertId () throws Exception { the User User = new new the User (); user.setUsername ( "INSERT mybaitis_last" ); user.setBirthday ( new new a Date ()); user.setSex ( "F" ); user.setAddress ( "District Beijing station" System.out.println ("Before executing the Save operation" + User); // execute preservation method userDAO.saveUser (User); System.out.println ( "save operation after performing" + User); } / ** * test update * / @Test public void testUpdate () throws Exception { the User User = new new the User (); user.setId ( 50 ); user.setUsername ( "mybaitis_update" ); user.setSex ( "F" ); // execute the query in all methods userDao.updateUser (user); } / * * * test delete * / @Test public void TestDelete () throws Exception { userDao.deleteUser ( 48 ); } / ** * test for the specified operation * / @Test public void testFindOne () throws Exception { the User User userDao.findUser = (50 ); System.out.println (User); } / ** * test operation fuzzy search * / @Test public void testFindLikeName () throws Exception { List<User> users = userDao.findByLikeName ( " % Small%" ); for (the User User: Users) { System.out.println (User); } } / ** * Total number of test queries the user * / @Test public void testFindTotal () { int COUNT = userDao.findTotal (); the System.out .println (COUNT); } }