The previous article "Javaweb Practical Mall Project Development (I)" has created entity classes and pagination tools. This article uses mybatis to create DAO layers.
In addition, mybatis API documentation can be used as a reference
1. The use of mybatis
1. Introduce a shelf package
Here I introduce mybatis and mysql packages into lib
2. Write Config.xml to configure the database environment
Post the code first, then explain one by one
<?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="Config.properties"/> <typeAliases> <package name="com.model"/> </typeAliases> <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> <!--Second Environment--> <environment id="publish"> <transactionManager type="JDBC"/> <dataSource type="POOLED"/> </environment> </environments></configuration>The first step is to introduce the XML file format, that is, dtd, which needs to be copied directly from the template provided by mybatis.
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
Question 1
The properties function is to configure the corresponding properties file, resource specifies the corresponding route, and we can configure the database driver, url, username, password, etc. in the properties file. Refer to the following. In this way, mybatis will automatically read the following parameters, and you can use ${} to reference it in the xml.
driver = com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/shop username=root password=123456
Question 2
typeAliases configures alias under the specified path. We can configure a single alias single name<typeAlias type="com.model.User" alias="User"/> In this way, com.model.User is changed to alias User. There is no need to write all names later. You only need User to replace batch modification<package name="com.model"/>. In this way, you can modify all the classes of a package, and the default alias is the entity class name.
Question 3
Environments are used to configure the database environment, and can configure multiple environments, such as development environment and release environment, default refers to the default environment
Note that there is no s in the environment, which represents an environment under environments. It is distinguished by id, so id must be unique.
transactionManager represents the connection database type, JDBC connects to java
DataSource configures data source mode, pooled is the connection pool mode. For other modes, you can go to the official document to check it out and choose according to your needs.
property is to configure the database connection. Don't move the name, modify the value="driver". Here is the use of {} to read the configuration in the top properties file. Pay attention to matching the name to read it.
3. Write mapper mapping sql statement
Here I write UserDao load method, that is, read a user based on id. The following code is equivalent to the public User load(int id) function. For mybatis, there are two types of replacement #{} replacement will be automatically quoted according to the type, such as the string type #{name} replaced with 'name'. The other is ${} replacement, which is directly replaced in the original format and will not add other things.
<?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> <select id="load" parameterType="int" resultType="User"> SELECT * from user WHERE id=#{id} </select></mapper>The first step is to introduce the dtd header file and formulate the rules for the xml file
select tag, indicating that it is currently a select statement
The id attribute is equivalent to the function name, referenced by id
parameterType attribute, which represents the incoming parameter type, can specify the basic type or a custom type. If it is a custom type, its get method will be automatically called to obtain its attributes.
The resultType property, return value type, can directly customize the type, and will automatically call the set method to set the query parameters and use more properties in subsequent articles.
4. Call mapper map
Before calling, you need to configure the mapping in Config.xml first. Note that the xml configured here is the file path.
<mappers> <mapper resource="com/model/User.xml"/></mappers>
Then write a test class
public static void main(String[] args) { try { InputStream is = Resources.getResourceAsStream("Config.xml");//Read the configuration file SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//Use the configuration file to create factory SqlSession session = factory.openSession();//Get session User user = session.selectOne(User.class.getName()+".load",1);//Call the load function System.out.println(user.getNickname());//Output nickname session.close();//Close session } catch (IOException e) { e.printStackTrace(); } } result:
5.Sqlsession tool class
Writing test classes like the one above is too troublesome, so I encapsulate Sqlsession to facilitate the use of the DAO layer
package com.util;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;import java.io.InputStream;/** * Created by nl101 on 2016/2/23. */public class SessionUtil { private static SqlSessionFactory factory= null; static { try { InputStream is = Resources.getResourceAsStream("Config.xml");//Read configuration file factory = new SqlSessionFactoryBuilder().build(is);//Create factory using configuration file } catch (IOException e) { e.printStackTrace(); } } /** * Get session * @return */ public static SqlSession getSession(){ return factory.openSession(); } /** * Close session * @param session */ public static void closeSession(SqlSession session){ if (session!=null) session.close(); session = null; }}The above is the basic use of mybatis, and now it starts to encapsulate the DAO layer
2. Encapsulate DAO
1.UserDao.java
public User load(int id) Get a User based on id
It has been written above
public boolean add(User user) add a user
XML code
<!--Add a user--> <insert id="add" parameterType="User"> INSERT INTO user VALUES (null,#{username},#{password},#{nickname},#{type}) </insert>JAVA Code
/** /** * Add a user* @param user The user to be added* @return true Success*/ public boolean add(User user){ int isAdd = 0; SqlSession session = SessionUtil.getSession(); try { isAdd = session.insert(User.class.getName()+".add",user); session.commit();//Submit} catch (Exception e) { session.rollback();//Rolleback if submission fails} finally { SessionUtil.closeSession(session); } System.out.println(isAdd); return isAdd>0; }public boolean delete(int id) delete a userxml code
<!--Delete a user--> <delete id="delete" parameterType="int"> DELETE FROM user WHERE id=#{id} </delete>Java code
/** *Delete user based on id* @param id To delete the user's id * @return true Success */ public boolean delete(int id){ int isDelete = 0; SqlSession session = SessionUtil.getSession(); try { isDelete = session.delete(User.class.getName()+".delete",id); session.commit(); } catch (Exception e) { session.rollback();//Failed to return System.out.println("Delete user failed"); e.printStackTrace(); } finally { SessionUtil.closeSession(session); } return isDelete>0; }public boolean update(User user) update userxml code
<!--Modify a user--> <update id="update" parameterType="User" > UPDATE user SET username=#{username},password=#{password},nickname=#{nickname},type=#{type} where id=#{id} </update>Java code
/** *Update user* @param user The user to be updated* @return true Success*/ public boolean update(User user){ int isUpdate = 0; SqlSession session = SessionUtil.getSession(); try { isUpdate = session.delete(User.class.getName()+".update",user); session.commit(); } catch (Exception e) { session.rollback();//Failed Return System.out.println("Update failed"); e.printStackTrace(); } finally { SessionUtil.closeSession(session); } return isUpdate>0; }public User login(String username, String password) determines whether the user existsxml code
<!--User Login Judgment--> <select id="login" parameterType="String" resultType="User"> SELECT * FROM user WHERE username=#{username} </select>Java code
/** * Determine whether a user exists* @param username Username* @param password Password* @return Existence Return User Does Not Exist Return null */ public User login(String username, String password){ User user = null; SqlSession session = SessionUtil.getSession(); try { user = session.selectOne(SOAPBinding.Use.class.getName()+".login",username); // When the password is incorrect, set user to null if (!user.getPassword().equals(password)){ user = null; } } finally { SessionUtil.closeSession(session); } return user; } public Pager find(String name,String sort,String order) pagination processing xml code:
Dynamic SQL is used here. Regarding dynamic SQL, it is the use of tags such as where, if, choose, etc. You can refer to the official document. In addition, in mybatis, the concept of null does not exist. For example, you pass user=null, but when replacing, it is replaced with a "null" string. If this value is not available, it is null.
<!--Pagination code--> <select id="find" parameterType="Map" resultType="User"> SELECT * from user <if test="name!=null">WHERE (username LIKE #{name} or nickname LIKE #{name})</if> ORDER BY ${sort} ${order} LIMIT #{pageStart},#{pageSize} </select> <!--Total number of page records--> <select id="findcount" parameterType="Map" resultType="int"> SELECT count(*) from user <if test="name!=null">WHERE (username LIKE #{name} or nickname LIKE #{name})</if> </select>Java code: Overall, it is still based on the pagination designed by the previous article
/** *Page query based on specified conditions* @param name query conditions, null represents unconditional* @param sort sort sort condition, null represents sort by id* @param order sort condition, null represents ascending order* @return */ public Pager<User> find(String name,String sort,String order){ int pageStart = SystemContext.getPageStart();//Page start int pageSize = SystemContext.getPageSize();//Page size Pager<User> pagers = new Pager<>(); Map<String,Object> maps = new HashMap<>(); if (name!=null && !name.equals("")){ name = "%"+name+"%"; maps.put("name",name); } if (sort==null || sort.equals("")){ sort = "id";//Sorted by id by default} if (order==null || order.equals("")){ order = "asc";//Default sort} maps.put("sort",sort); maps.put("order",order); maps.put("pageStart",pageStart); maps.put("pageSize",pageSize); SqlSession session = SessionUtil.getSession(); List<User> datas = null; try { datas = session.selectList(User.class.getName()+".find",maps);//Get record pagers.setDatas(datas); pagers.setPageSize(pageSize); pagers.setPageStart(pageStart); int totalRecord = session.selectOne(User.class.getName()+".findcount",maps);//Get the total number of records pagers.setTotalRecord(totalRecord); pagers.setPageIndex(pageStart/pageSize+1); } finally { SessionUtil.closeSession(session); } return pages; } Current project structure
In the next article, I will write a general BaseDao to facilitate the writing of code. And continue to learn the use of other properties of mybatis. Thank you for your reading.