MyBatis关联查询:多对多(注解实现)

数据表

MyBatis关联查询:多对多(注解实现)_第1张图片

项目框架搭建

第一步:创建Maven项目

  • 添加Maven依赖:
<dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
        <scope>testscope>
    dependency>

    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
    dependency>

    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.10version>
    dependency>

    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>8.0.18version>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.4version>
    dependency>
  • 指定Mapper XML文件在mybatis-config.xml中的配置有效,强制部署resources目录到classes
<resources>
    <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
            <include>**/*.xmlinclude>
        includes>
    resource>
    <resource>
        <directory>${basedir}/src/main/resourcesdirectory>
    resource>
resources>

第二步:配置文件

  • log4j.properties
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] %-5p [%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  
  • mysql.properties
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);
        }
    }
}

代码实现

实体类

  • Course.javat
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Course implements Serializable {
    
    private static final long serialVersionUID = -6376901343663894314L;
    
    private Integer id;
    private String name;
    private String intro;

}
  • Stu
@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



<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接口

  • CourseDao
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);
}
  • StuDao
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);
        }
    }

}

你可能感兴趣的:(#,MyBatis,MyBatis关联查询,MyBatis多对多查询,MyBatis多对多注解实现)