數據表
項目框架搭建
第一步:創建Maven項目
< dependency>
< groupId> junit</ groupId>
< artifactId> junit</ artifactId>
< version> 4.12</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> log4j</ groupId>
< artifactId> log4j</ artifactId>
< version> 1.2.17</ version>
</ dependency>
< dependency>
< groupId> org.projectlombok</ groupId>
< artifactId> lombok</ artifactId>
< version> 1.18.10</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 8.0.18</ version>
</ dependency>
< dependency>
< groupId> org.mybatis</ groupId>
< artifactId> mybatis</ artifactId>
< version> 3.5.4</ version>
</ dependency>
指定Mapper XML文件在mybatis-config.xml中的配置有效,強制部署resources目錄到classes
< resources>
< resource>
< directory> src/main/resources</ directory>
< includes>
< include> **/*.xml</ include>
</ includes>
</ resource>
< resource>
< directory> ${basedir}/src/main/resources</ directory>
</ resource>
</ resources>
第二步:配置文件
log4j. rootLogger= DEBUG, Console
#Console
log4j. appender. Console= org. apache. log4j. ConsoleAppender
log4j. appender. Console. layout= org. apache. log4j. PatternLayout
log4j. appender. Console. layout. ConversionPattern= % d [ % t] % - 5 p [ % c] - % m% n
log4j. logger. java. sql. ResultSet= INFO
log4j. logger. org. apache= INFO
log4j. logger. java. sql. Connection= DEBUG
log4j. logger. java. sql. Statement= DEBUG
log4j. logger. java. sql. PreparedStatement= DEBUG
driver= com. mysql. cj. jdbc. Driver
url= jdbc: mysql: / / 127.0 .0 .1 / db_test? useSSL= false & serverTimezone= CST
username= root
password= root
第三步:工具類MyBatisUtil
public class MyBatisUtil {
private static String CONFIG_FILE_LOCATION = "mybatis-config.xml" ;
private static final ThreadLocal< SqlSession> threadLocal = new ThreadLocal < SqlSession> ( ) ;
private static SqlSessionFactory sessionFactory;
static {
try {
Reader reader = Resources. getResourceAsReader ( CONFIG_FILE_LOCATION) ;
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder ( ) ;
sessionFactory = builder. build ( reader) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
public static SqlSession getSession ( ) {
SqlSession session = threadLocal. get ( ) ;
if ( session == null) {
session = ( sessionFactory != null) ? sessionFactory. openSession ( ) : null;
threadLocal. set ( session) ;
}
return session;
}
public static void closeSession ( ) {
SqlSession session = threadLocal. get ( ) ;
if ( session != null) {
session. close ( ) ;
threadLocal. set ( null) ;
}
}
}
代碼實現
實體類
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Course implements Serializable {
private static final long serialVersionUID = - 6376901343663894314 L;
private Integer id;
private String name;
private String intro;
}
@Data
@ToString ( exclude = "courses" )
@AllArgsConstructor
@NoArgsConstructor
public class Stu {
private Integer id;
private String name;
private Boolean gender;
private List< Course> courses ;
}
第一步:創建mybatis-config.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>
< properties resource = " mysql.properties" > </ properties>
< settings>
< setting name = " logImpl" value = " STDOUT_LOGGING" />
</ settings>
< 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>
< mapper class = " com.hc.many2many.dao.StuDao" />
< mapper class = " com.hc.many2many.dao.CourseDao" />
</ mappers>
</ configuration>
第二步:創建Dao接口
public interface CourseDao {
@Select ( "select * from tb_course where id in (select course_id from tb_stu_course where stu_id =#{stuId})" )
List< Course> selectCourseByStuId ( Integer stuId) ;
}
public interface StuDao {
@Select ( "select * from tb_stu where name= #{name}" )
@Results ( {
@Result ( id= true , column = "id" , property = "id" ) ,
@Result ( column = "name" , property = "name" ) ,
@Result ( column = "gender" , property = "gender" ) ,
@Result (
column = "id" ,
property = "courses" ,
many = @Many ( select = "com.hc.many2many.dao.CourseDao.selectCourseByStuId" , fetchType = FetchType. LAZY)
)
} )
List< Stu> selectStuWithCouseByStuName ( String name) ;
}
測試代碼
public class StuCourseDaoTest {
@Test
public void selectStuWithCouseByStuName ( ) {
SqlSession session = MyBatisUtil. getSession ( ) ;
StuDao stuDao = session. getMapper ( StuDao. class ) ;
List< Stu> stuList = stuDao. selectStuWithCouseByStuName ( "lisi" ) ;
System. out. println ( stuList) ;
for ( Stu stu : stuList) {
stu. getCourses ( ) . forEach ( System. out: : println) ;
}
}
}