前言:本次简单实例适合如我一般开始学习mybatis的新手,需要对mybatis有一定基础和实践,掌握基本的类的会话工厂、类的实例化、注解、结果集映射等操作。
关注我,一起学习!!
目录
1、配置Mybatis依赖以及配置文件
1、pom文件引入相关依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.mybatis</groupId>
<artifactId>JavaEEWork3</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compilr.target>16</maven.compilr.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2、mybatis配置文件
<?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="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<!-- mapping文件路径配置 -->
<mappers>
<mapper class="com.itheima.dao.StudentMapper"/>
<mapper class="com.itheima.dao.CourseMapper"/>
</mappers>
</configuration>
3、数据库驱动以及账户密码配置自行解决
2、创建数据库及数据表
1、在MySQL中创建数据表
1、创建学生表
create table Students(
id int primary key,
name varchar(20) not null,
age int not null
);
insert into Students(id,name,age) values(1,"小明",19),(2,"小红",20),(3,"小张",21),(4,"小李",20),(5,"小赵",19);
2、创建课程表
create table Course(
id int primary key auto_increment,
cname varchar(20) not null,
cteacher varchar(10) not null,
cpoint int not null
);
insert into Course (id,cname,cteacher,cpoint) values(1,"Java程序设计","李小爱",4),(2,"软件工程","张子期",2),(3,"马克思主义理论","吴光许",4),(4,"体育健康","王不易",2);
3、创建中间表并设置外键
create table Course_M(
id int primary key auto_increment,
students_id int not null,
courses_id int not null,
foreign key(students_id) references Students(id)
)
insert into Course_M(id,students_id,courses_id) values(1,1,2),(2,1,4),(3,2,3),(4,2,1);
3、编写POJO类
1、Student持久层
package com.itheima.pojo;
import java.util.List;
public class Student {
private int id;
private String name;
private int age;
private List<Course>CourseList;
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 int getage() {
return age;
}
public void setage(int age) {
this.age =age;
}
public List<Course> getCourseList()
{
return CourseList;
}
public void setCourseList(List<Course> CourseList)
{
this.CourseList = CourseList;
}
@Override
public String toString()
{
return "\nStudent [id=" +id+",name="+name+",age="+age+",CourseList="+CourseList+"]";
}
}
2、Course持久层
package com.itheima.pojo;
public class Course {
private int id;
private String CourseName;
private String CourseTeacher;
private int CoursePoint;
public int getid()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public String getCourseName()
{
return CourseName;
}
public void setCourseName(String CourseName)
{
this.CourseName=CourseName;
}
public String getCourseTeacher()
{
return CourseTeacher;
}
public void setCourseTeacher(String CourseTeacher)
{
this.CourseTeacher=CourseTeacher;
}
public int getCoursePoint()
{
return CoursePoint;
}
public void setCoursePoint(int CoursePoint)
{
this.CoursePoint=CoursePoint;
}
@Override
public String toString()
{
return "\nCourse [id="+id+",CourseName="+CourseName+",CourseTeacher="+CourseTeacher+",CoursePoint="+CoursePoint+"]";
}
}
4、编写工具类
package com.itheima.utils;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Utils {
private static SqlSessionFactory sqlSessionFactory=null;
static {
try {
Reader reader= Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static SqlSession getSession()
{
return sqlSessionFactory.openSession();
}
}
5、编写接口映射文件
1、CourseMapper
package com.itheima.dao;
import com.itheima.pojo.Course;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface CourseMapper {
@Select("select* from Course where id in (select courses_id from Course_M where students_id=#{id})" )
@Results({@Result(id = true ,column = "id",property ="id" ),
@Result(column = "cname",property = "CourseName"),
@Result(column = "cteacher",property = "CourseTeacher"),
@Result(column = "cpoint",property = "CoursePoint")
})
List<Course> FindCourseByStudentId(int students_id);
}
2、StudentMapper接口映射
package com.itheima.dao;
import com.itheima.pojo.Student;
import org.apache.ibatis.annotations.*;
public interface StudentMapper {
@Select("select * from Students where id=#{id}")
@Results({@Result(id = true,column = "id",property = "id"),
@Result(column = "age",property = "age"),
@Result(column = "name",property = "name"),
@Result(column ="id",property ="CourseList",
many=@Many(select="com.itheima.dao.CourseMapper.FindCourseByStudentId"))
})
Student FindCourseById(int id);
}
6、编写测试类实现程序功能
实例化工具类,开启会话,获取映射文件,执行接口中的方法进行查询,提交事务,关闭事务。
查询学号为2的学生信息及其选课信息:
package Test;
import com.itheima.dao.CourseMapper;
import com.itheima.dao.StudentMapper;
import com.itheima.pojo.Course;
import com.itheima.pojo.Student;
import com.itheima.utils.Utils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Test;
public class Stu_ClaTest {
private SqlSession session;
@Test
public void Test()
{
Utils utils=new Utils();
session=utils.getSession();
StudentMapper studentMapper=session.getMapper(StudentMapper.class);
Student student=studentMapper.FindCourseById(2);
System.out.println(student.toString());
}
@After
public void destory()
{
session.commit();
session.close();
}
}
7、查询结果
码字不易点个赞呗!