1. Interface binding xml file (it convenient manner with respect to annotations associated table)
2. The entity class field attributes do not match the process
3. Union-table query
First, the interface binding xml file
1. Right-engineering recommendations Source Folder file named resources folder for storing config.xml, mapping mappper package, properties file
(After the contents of the file will be compiled in a folder bin file)
Built-interface 2. dao package
1. Under the mapping file <mapper> tag namespace attributes to match and where the packet interface 2. The operation id tag to the same method name corresponding to the interface ==> as interface implementation class public interface RoleDao { public void addRole (Role Role ); public List <Role> selectById (@Param ( "min") int min, the Param @ ( "max") int max); } // @param annotation named parameters, the default is [0, 1, param1, param2 ] see supplementary five <xml Version = "1.0" encoding = "UTF-8"??> <DOCTYPE Mapper the PUBLIC! "- // mybatis.org//DTD Mapper 3.0 // EN" "http://mybatis.org /dtd/mybatis-3-mapper.dtd "> <Mapper namespace =" com.zhiyou100.yj.dao.OrderDao "> <INSERT ID =" addRole "the parameterType =" com.zhiyou100.yj.bean.Role"> insert into role(uname,description) values(#{uname},#{description}) </insert> <select id="selectById" resultType="com.zhiyou100.yj.bean.Role"> select * from role where id>#{min} and id<=#{max}; </select> </mapper>
3. Test
class RoleMapperTest { static SqlSession session=null; static RoleDao roleDao=null; @BeforeAll static void setUpBeforeClass() throws Exception { Reader reader = Resources.getResourceAsReader("config.xml"); SqlSessionFactory SessionFactory = new SqlSessionFactoryBuilder().build(reader); session = SessionFactory.openSession(); roleDao = session.getMapper(RoleDao.class); } @Test void testAddRole() { Role role=new Role("李大炳","助理"); roleDao.addRole(role); } @Test void testSelectById() { List<Role> roles = roleDao.selectById(3, 4); System.out.println(roles); } @AfterAll static void tearDownAfterClass() throws Exception { session.commit(); } }
A supplement: the interface binding xml how to pass parameters
Direct transfer participants reported the following exception: Error querying the Database. The Cause: org.apache.ibatis.binding.BindingException: the Parameter . 'The uname' Not found the Available Parameters are [0,. 1 , the param1, param2] This is because the default parameters mabatis package to the map, it is the key in two forms [ 0, 1 , the param1, param2] to solve this problem there are three ways: 1 , the parameter to a default parameter Mybatis [arg0, argX, param1, paramX ] (X corresponding to the number of parameters); 2 , the encapsulated as a parameter the JavaBean, and the interface parameter to the the JavaBean; . 3 , method map parameter passing; 4, @Param annotation interface parameters; (recommended)
Second, the entity class field names and attributes do not match
public class Role { Private int ID; Private String the uname; Private String Description; } <Update ID = "updateRole"> Update Role SET role_uname = # {the uname}, role_description = # {Description} WHERE role_id = # {ID} </ update> error :( results do not match the properties of the heart is displayed as null) query org.apache.ibatis.binding.BindingException: Type interface . com.zhiyou100.yj.dao.RoleDao iS not at The MapperRegistry Known to one: for the field from alias to match the entity class attribute <select id = "selectById" parameterType = "int" resultType = "com.zhiyou100.yj.bean.Role"> SELECT role_uname name, role_description Description, role_id ID from Role WHERE role_id = # {ID} </ SELECT> Method II: resultMap attribute substitution resultType properties, and the write-field attributes control relationship resultMap the <select id = "selectById" parameterType = " int "The resultMap =" rolemap "> SELECT * WHERE role_id from Role = # {ID} </ SELECT> <The resultMap type =" com.zhiyou100.yj.bean.Role "ID =" rolemap "> <- type!: shows a correspondence table of the entity class, the return type of analogy -> <ID = column "role_id" = Property "ID" /> <Result column = "role_description" Property = "Description" /> <Result column = "role_uname "property =" name "/> </resultMap>
Third, the United-table query
1, many-to-query; one query (as a property of the other party, query results encapsulated object) // as a class corresponding to each class 2, many queries (one of multiple configuration set as a properties, to package the query result set) // as each class comprising a plurality of student one , many-to-query; query one public class Clazz { Private int CID; Private String cName; Private int teacheId; Private Teacher Teacher; // associated target teacher Private List <student> students.; // associated with student object set } public class teacher { Private int ID; Private String tName; } public class Student { private int sId; private String sName; private int classId; } <!-- 一对一联表 --> <select id="selectClazzById" resultMap="ClazzMap"> select * from class c,teacher t where c.teacher_id=t.t_id and c_id=#{id} </select> <resultMap type="com.zhiyou100.yj.bean.Clazz" id="ClazzMap"> <id column="c_id" property="cId"/> <result column="c_name" property="cName"/> <result column="teacher_id"= Property "teacheId" /> Property: Teacher Object Properties <-! -> The javaType: Teacher object type <Association Property = "Teacher" the javaType = "com.zhiyou100.yj.bean.Teacher"> <ID = column "t_id" = Property "ID" /> <Result column = "t_name" = Property " tName "/> </ Association> </ The resultMap> <-! nested one -> <SELECT ID =" selectClazzById2 "The resultMap =" ClazzMap2 "> SELECT * from class WHERE c_id CID = # {} <! - query class id, class id according to the query result obtained in the further inquiry -> </ SELECT> <the resultMap type = "com.zhiyou100.yj.bean.Clazz" id = "ClazzMap2"> <id column = "c_id "Property =" CID "/> <result column="c_name" property="cName"/> <result column="teacher_id" property="teacheId"/> <!-- property:Teacher对象属性 javaType: Teacher Object Type select: corresponding to the further query id (another query table) column: Condition field (the foreign key field) corresponding to the further query -> <Association Property = "Teacher" the javaType = "com.zhiyou100.yj.bean.Teacher" SELECT = "selectTeacher" column = "teacher_id "> </ Association> </ The resultMap> <- writing a:! attribute fields do not match, aliases -> <SELECT ID =" selectTeacher "the resultType =" com.zhiyou100.yj.bean.Teacher "> SELECT t_id ID, t_name tName from Teacher WHERE t_id = # {} teacher_id </ SELECT> <- writing II:! attribute fields do not match, The resultMap -> <SELECT ID = "selectTeacher" The resultMap = "TeacherMap"> SELECT * from Teacher t_id = WHERE # teacher_id} { </select> <resultMap type="com.zhiyou100.yj.bean.Teacher" id="TeacherMap" > <id column="t_id" property="id"/> <result column="t_name" property="tName"/> </resultMap> <!-- 一对多联表 --> <select id="selectClazzById3" resultMap="ClazzMap3"> select * from class c,student s,teacher t where c.c_id=s.class_id and t.t_id=c.teacher_id and c.c_id=#{id}; </select> <resultMap type="com.zhiyou100.yj.bean.Clazz" id="ClazzMap3"> <id column="c_id" property="cId"/> <result column="c_name" property="cName"/> <result column="teacher_id" property="teacheId"/> <association property="teacher" javaType="com.zhiyou100.yj.bean.Teacher"> <!--对象类型:teacher--> <id column="t_id" property="id"/> <result column="t_name" property="tName"/> </association> <collection property="students" ofType="com.zhiyou100.yj.bean.Student"> <!-- 集合类型:students;ofType:集合泛型的数据类型--> <id column="s_id" property="sId"/> <result column="s_name" property="sName"/> <result column="class_id" property="classId"/> </collection> </resultMap> <!-- 一对多嵌套 --> <select id="selectClazz4" resultMap="ClazzMap4"> select * from class where c_id=#{cid} </select> <resultMap type="com.zhiyou100.yj.bean.Clazz" id="ClazzMap4"> <id column="c_id" property="cId" /> <result column="c_name" property="cName" /> <result column="teacher_id" property="teacheId" /> <association property="teacher" javaType="com.zhiyou100.yj.bean.Teacher" select="selectTeacher" column="teacher_id"> </association> <collection property="students" ofType="com.zhiyou100.yj.bean.Student" select="selectStudent" column="c_id"> </collection> </resultMap> <select id="selectTeacher" resultType="com.zhiyou100.yj.bean.Teacher"> select t_id id,t_name tName from teacher where t_id=#{teacher_id} </select> <select id="selectStudent" resultType="com.zhiyou100.yj.bean.Student"> select s_id sId,s_name sName,class_id classId from student where class_id=#{c_id} </select>
Supplementary two: MyBatis in the difference between the $ and #
$: Does not add to the content parsing "" is spliced sql statement, sql injection hazard exists passed is a column name or table name, you can use the $ EG: If the value is the value of Anything 'OR' the X-'= 'x, then the sql statement would be from User * WHERE name SELECT =' Anything 'or' X '=' X ' #: parsing the content is added , "", using a placeholder, the passed # {xxx} "?" the content is escaped, then replace the contents of EG: the SELECT * Student from the WHERE name = 'Anything \' or \ 'the X-\' = \ 'the X-'
Supplementary 3: How to produce returns add an object id
<insert id="addRole" useGeneratedKeys="true" keyProperty="id">
insert into role(uname,description) values(#{uname},#{description})
</insert>