直接上代码
MySQL数据参照自己的
每种都有两种方法哟
多对一
第一步:依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j 日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
第二步:配好mybatis-confing.xml,log4j.propeties,db.propeties文件
<?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 文件-->
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<environments default="development">
<environment id="development">
<!--transactionManager 事务管理器 JDBC-->
<transactionManager type="JDBC"/>
<!--dataSource 数据源 POOLED -->
<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),这些映射器的 XML 映射文件包含了 SQL 代码和映射定义信息。-->
<mappers>
<mapper resource="com/mapper/StudentMapper.xml"/>
<mapper resource="com/mapper/TeacherMapper2.xml"/>
<package name="com.mapper2"/>
</mappers>
</configuration>
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=D:axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/people?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
username=root
password=root
第三步:实体类
package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private Teacher teacher;
}
package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
第四步:工具类
package com.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.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//定义核心配置文件的路径
String resource = "mybatis-config.xml";
// Resources 的工具类 的方法 加载资源文件 得到输入流
InputStream is = Resources.getResourceAsStream(resource);
// 创建 建造者模式,去建造一个工厂
// 建造者模式:SqlSessionFactoryBuilder()
// 工厂模式: sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}catch (Exception e){
e.printStackTrace();
}
}
public static SqlSession sqlSession(){
return sqlSessionFactory.openSession(true);
}
}
第五步:mapper层
package com.mapper;
import com.pojo.Student;
import java.util.List;
public interface StudentMapper {
List<Student> getStudent(int tid);
List<Student> getStudent2(int tid);
}
<?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">
<!--namespace:命名空间 绑定接口的全路径-->
<mapper namespace="com.mapper.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from student where tid = #{tid};
</select>
<resultMap id="StudentTeacher" type="com.pojo.Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="com.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.pojo.Teacher">
select * from teacher where id =#{id};
</select>
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname,t.id id from student s,teacher t where s.tid = t.id and s.tid = #{tid};
</select>
<resultMap id="StudentTeacher2" type="com.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.pojo.Teacher">
<result property="id" column="id"/>
<result property="name" column="tname"/>
</association>
</resultMap>
</mapper>
第六步:测试
package com;
import com.mapper.StudentMapper;
import com.mapper.TeacherMapper2;
import com.pojo.Teacher2;
import com.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
public class Mybatis02 {
@Test
public void demo01(){
SqlSession sqlSession = MybatisUtils.sqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.getStudent(1).forEach(System.out::println);
sqlSession.close();
}
@Test
public void demo02(){
SqlSession sqlSession = MybatisUtils.sqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.getStudent2(2).forEach(System.out::println);
sqlSession.close();
}
}
一对多
一二四步同上
第三步:实体类
package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student2 {
private int id;
private String name;
private int tid;
}
package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher2 {
private int id;
private String name;
private List<Student2> student2s;
}
第五步:mapper层
package com.mapper;
import com.pojo.Teacher2;
import org.apache.ibatis.annotations.Param;
public interface TeacherMapper2 {
Teacher2 getStudent(@Param("tid") int id);
Teacher2 getStudent2(@Param("tid") int id);
}
<?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">
<!--namespace:命名空间 绑定接口的全路径-->
<mapper namespace="com.mapper.TeacherMapper2">
<select id="getStudent" resultMap="teacher">
select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t
where t.id = #{tid} and t.id = s.tid
</select>
<resultMap id="teacher" type="com.pojo.Teacher2">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="student2s" ofType="com.pojo.Student2">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<select id="getStudent2" resultMap="teacher2">
select * from teacher where id = #{tid}
</select>
<resultMap id="teacher2" type="com.pojo.Teacher2">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="student2s" javaType="ArrayList" ofType="com.pojo.Student2" select="student" column="id"/>
</resultMap>
<select id="student" resultType="com.pojo.Student2">
select * from student where tid = #{tid}
</select>
</mapper>
第六步·:测试
package com;
import com.github.pagehelper.PageHelper;
import com.mapper.BookMapper;
import com.pojo.Book;
import com.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Mybatis01 {
@Test
public void test03(){
SqlSession sqlSession = MybatisUtils.sqlSession();
BookMapper mapper = sqlSession.getMapper(BookMapper.class);
PageHelper.startPage(1,2);
mapper.query().forEach(System.out::println);
sqlSession.close();
}
@Test
public void test04(){
SqlSession sqlSession = MybatisUtils.sqlSession();
BookMapper mapper = sqlSession.getMapper(BookMapper.class);
mapper.queryAll().forEach(System.out::println);
sqlSession.close();
}
}