Mybatis中多個對象包含同一個對象的處理操作
例如
關鍵字:association : 聯系 ,關聯 多個人可以關聯一個人。
首先做一些準備,如:實體類,工具類和Mybatis核心文件
實體類:
//老師實體類package com.MLXH.pojo;public class Teacher { private int id; private String name; public Teacher() { } public Teacher(int id, String name) {this.id = id;this.name = name; } public int getId() {return id; } public void setId(int id) {this.id = id; } public String getName() {return name; } public void setName(String name) {this.name = name; } @Override public String toString() {return 'Teacher{' +'id=' + id +', name=’' + name + ’’’ +’}’; }}
//學生實體類package com.MLXH.pojo;public class Student { private int id; private String name; private Teacher teacher; public Student() { } public Student(int id, String name, Teacher teacher) {this.id = id;this.name = name;this.teacher = teacher; } public int getId() {return id; } public void setId(int id) {this.id = id; } public String getName() {return name; } public void setName(String name) {this.name = name; } public Teacher getTeacher() {return teacher; } public void setTeacher(Teacher teacher) {this.teacher = teacher; } @Override public String toString() {return 'Student{' +'id=' + id +', name=’' + name + ’’’ +', teacher=' + teacher +’}’; }}
database.properties配置文件數據庫需要的數據
driver = com.mysql.jdbc.Driverurl = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8username = rootpassword = 123456
Mybatis工具類:mybatis-config.xml
<?xml version='1.0' encoding='UTF-8' ?><!DOCTYPE configurationPUBLIC '-//mybatis.org//DTD Config 3.0//EN''http://mybatis.org/dtd/mybatis-3-config.dtd'><configuration> <!--配置文件修改--> <properties resource='database.properties'/> <!--Mybatis設置--> <settings><!--默認日志實現--><!--<setting name='logImpl' value='STDOUT_LOGGING'/>--><!--Log4j實現--><setting name='logImpl' value='LOG4J'/> </settings> <!--配置別名--> <typeAliases><package name='com.MLXH.pojo'/> </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> </environments> <mappers><!--class對應的是一個接口類--><!--resource對應的是一個接口類的映射文件--><mapper resource='com/MLXH/dao/StudentMapper.xml'/> </mappers></configuration>
工具類:主要是為了使獲得sqlsession更為簡單方便
package com.MLXH.utils;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 java.io.IOException;import java.io.InputStream;//mybatis的工具類,重復的代碼的提純public class MyBatisUtils { //類變量不需要設置默認值; private static SqlSessionFactory sqlSessionFactory; static {//在maven中,所有的資源文件一般都放在resources目錄下,我們可以直接拿到。try { String resource = 'mybatis-config.xml'; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) { e.printStackTrace();} } //設置SqlSessionFactory公共的方法 public static SqlSessionFactory getSqlSessionFactory(){return sqlSessionFactory; } //獲得一個帶事務自動提交功能的SqlSession公共的方法 public static SqlSession getSqlSession(){//自動提交事務return sqlSessionFactory.openSession(true); }}
StudentDao接口
package com.MLXH.dao;import com.MLXH.pojo.Student;import java.util.List;public interface StudentDao { //獲得全部學生的信息以及對應的老師 List<Student> getStudents(); //獲得全部學生的信息以及對應的老師 List<Student> getStudentsTwo();}
針對于StudentDao接口的實現mapper文件:我們使用如下的方式來進行查詢
1.模擬數據庫思想:連表查詢StudentMapper.xml
<?xml version='1.0' encoding='UTF-8' ?><!DOCTYPE mapperPUBLIC '-//mybatis.org//DTD Mapper 3.0//EN''http://mybatis.org/dtd/mybatis-3-mapper.dtd'><!--namespace不能寫別名--><mapper namespace='com.MLXH.dao.StudentDao'> <!--遇到問題:學生類中關聯老師: 多個學生對應一個老師 --><!--解決問題方式一:按查詢結果嵌套處理,模擬數據庫思想;--> <select resultMap='StudentTeacher'>select * from mybatis.student </select> <resultMap type='Student'><id column='id' property='id'/><result column='name' property='name'/><!--屬性和字段對應 , 類和表對應 , 對象和記錄關聯一個字段需求:拿到老師這個類的屬性association : 關聯,多對一 column : 數據庫對應的列名 property : 對應屬性名 javaType : 多對一字段對應的Java類型 select : 關聯一個語句--><association column='tid' property='teacher' javaType='Teacher' select='getTeacher'/> </resultMap> <select resultType='Teacher'>select * from mybatis.teacher where id = #{id} </select></mapper>
測試類
@Test public void getStudents(){SqlSession sqlSession = MyBatisUtils.getSqlSession();StudentDao mapper = sqlSession.getMapper(StudentDao.class);List<Student> students = mapper.getStudents();for (Student student : students) { System.out.println('學生姓名:'+student.getName()+'t老師姓名:'+student.getTeacher().getName());} }2.模擬面向對象的思想
<?xml version='1.0' encoding='UTF-8' ?><!DOCTYPE mapperPUBLIC '-//mybatis.org//DTD Mapper 3.0//EN''http://mybatis.org/dtd/mybatis-3-mapper.dtd'><!--namespace不能寫別名!!!!!--><mapper namespace='com.MLXH.dao.StudentDao'> <!-- 解決方式二:一個resultMap解決 , 模擬面向對象的思想--> <select resultMap='StudentTeacher2'>select s.id,s.name,t.id as tid,t.name as tnamefrom mybatis.student as s, mybatis.teacher as twhere s.tid = t.id </select> <!--設置結果集映射ResultMap --> <resultMap type='Student'><id property='id' column='id'/><result property='name' column='name'/><!--直接關聯一個老師--><association property='teacher' javaType='Teacher'> <id property='id' column='tid'/> <result property='name' column='tname'/></association> </resultMap></mapper>
測試
@Testpublic void getStudentsTwo(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); StudentDao mapper = sqlSession.getMapper(StudentDao.class); List<Student> students = mapper.getStudentsTwo(); for (Student student : students) {System.out.println('學生姓名:'+student.getName()+'t老師姓名:'+student.getTeacher().getName()); }}
mybatis中遇到多對一的情況,要使用關聯映射處理:使用association
兩種處理思路:
數據庫思想 : 聯表查詢 OOP思想 :關聯對象Mybatis同時傳入多個對象及普通參數當傳入多個文件時,mapper接口文件的方法參數要使用@param(“xx”)注釋。
例子:mapper:
//Student是對象,age是String類型。int getPojo(@param('student') Student student, @param('age') String age );
xml:
<select resultMap='BaseResultMap'> select <include refid='Base_Column_List' /> from student where 1 = 1 <!-- 使用參數一(是個自己的對象) --> <if test='student.id != null'>and id = #{student.id} </if> <!-- 使用參數二 String類型 --> <if test='age!= null'>and age = #{age} </if></select>
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
