原理:
入门程序:
注意:
1,要测试,需要把配置好的文件都复制到测试资源文件夹里面,
2,配置的映射文件需要加载进核心文件的mapper里。
1,导入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2,在resources里创建一个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>
<environments default="development">
<environment id="development">
<!-- JDBC的事务,现在由Mybatis控制 -->
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/java2?serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
</mappers>
</configuration>
3,配置日志文件 log4j.properties
# 全局日志配置
log4j.rootLogger=ERROR, stdout
# MyBatis 日志配置
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4,写实体类
5,写sql的映射文件
<?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">
<mapper namespace="basicInfor">
<select id=""> </select>
<insert id=""></insert>
<delete id=""></delete>
<update id=""></update>
</mapper>
(namespace 名空间,可以对sql进行分类的一个管理包的概念类型)
6,写测试代码
package org.example;
import static org.junit.Assert.assertTrue;
import entity.BasicInfor;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void testFindBySID() throws IOException {
//1,读取核心配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//2.获取会话工厂
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
//3.获取sqlsession
SqlSession sqlSession=sqlSessionFactory.openSession();
//4,执行crud
// 第一个参数:要调用的方法(通过名空间和ID共同标识)
// 第二个参数:参数
BasicInfor basicInfor= sqlSession.selectOne("basicInfor.findBySId",1954651320);
System.out.println(basicInfor);
sqlSession.close();
}
}
作业:(增删改查)
传统DAO模式:
<?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> <environments default="development"> <environment id="development"> <!-- JDBC的事务,现在由Mybatis控制 --> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/hqusys?serverTimezone=UTC" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="StudentDao.xml"></mapper> <!--<mapper resource="TeacherDao.xml"></mapper>--> </mappers> </configuration>
<?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"> <mapper namespace="studentDao"> <select id="findBySId" parameterType="int" resultType="entity.Student"> select * from student where sid=#{0} </select> <insert id="addStu" parameterType="entity.Student"> insert into student(sName,sId,form,sClass,college,hTeacher,iD,date1) values(#{sName},#{sId},#{form},#{sClass},#{college},#{hTeacher},#{iD},#{date1}); </insert> <delete id="deleStuById" parameterType="int"> delete from student where sId=#{sId} </delete> <update id="updateStu" parameterType="entity.Student"> update student set sName=#{sName} where sId=#{sId} </update> <select id="findAll" resultType="entity.Student"> select * from student </select> </mapper>
import entity.Student; 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 org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.sql.Date; import java.sql.Time; import java.util.LinkedList; import java.util.List; public class testApp { SqlSessionFactory sqlSessionFactory; InputStream inputStream; SqlSession sqlSession; @Before public void begin() throws IOException { inputStream= Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); sqlSession=sqlSessionFactory.openSession(); } @Test public void testfindBySId(){ Student student=sqlSession.selectOne("studentDao.findBySId",1925123031); System.out.println(student); } @Test public void tesAddStu(){ java.util.Date d = new java.util.Date(); java.sql.Date date = new java.sql.Date(d.getTime()); Student student=new Student(); student.setCollege("计算机"); student.setDate1(date); student.setForm(2011); student.sethTeacher(111111); student.setiD("810000000110000002"); student.setsClass("建筑2班"); student.setsId(1925123031); student.setsName("王五"); sqlSession.insert("studentDao.addStu",student); } @Test public void testDeleteStuBySId(){ Student student=sqlSession.selectOne("studentDao.deleStuById",1925123031); } @Test public void tesUpdateStu(){ Student student=new Student(); student.setsName("Kenneth"); student.setsId(1925123031); sqlSession.update("studentDao.updateStu",student); } @Test public void testfindAll(){ List<Student>list=sqlSession.selectList("studentDao.findAll"); for (Student s:list ) { System.out.println(s); } } @After public void end(){ sqlSession.commit(); sqlSession.close(); } }
最后的commit很重要,没有的话,即使代码没错误,数据也不会入库!
Mapper 代理开发:
mapper的代码模式和我们之前接触的dao和dao.impl的这个思路一致。就变成:
- 需要写一个dao接口:放着crud的方法
- 接口需要有一个实现类:这个实现类就是刚刚映射文件,但是需要匹配某些规则
步骤:
- 编写dao接口
- 编写mapper.xml,相当是到接口的实现类,必须匹配以下规则
- Mapper.xml的nameSpace要和接口路径一致(包名+类名)
- Mapper.java中的方法名和Mapper.xml中ID的名称要一致
- Mapper.java中的方法参数类型和Mapper.xml中paramterType的类型要一致
- Mapper.java中的返回值类型和Mapper.xml中resultType的类型要一致
作业: =================================== Test.JAVA ===================================== import dao.StudentDao; import dao.TeacherDao; import entity.Student; import entity.Teacher; 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 org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class TestAPP2 { SqlSessionFactory sqlSessionFactory; InputStream inputStream; SqlSession sqlSession; TeacherDao teacherDao; @Before public void begin() throws IOException { inputStream= Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); sqlSession=sqlSessionFactory.openSession(); teacherDao=sqlSession.getMapper(TeacherDao.class); } @Test public void testFindAll(){ StudentDao studentdao=sqlSession.getMapper(StudentDao.class); List<Student>list=studentdao.findAll(); for (Student s:list ) { System.out.println(s); } } @Test public void testAddStu(){ java.util.Date d = new java.util.Date(); java.sql.Date date = new java.sql.Date(d.getTime()); Student student=new Student(); student.setCollege("计算机学院"); student.setDate1(date); student.setForm(2023); student.sethTeacher(333333); student.setiD("810000000110000003"); student.setsClass("新传3班"); student.setsId(1925123033); student.setsName("老六"); StudentDao studentdao= sqlSession.getMapper(StudentDao.class); studentdao.addStu(student); } @Test public void testFindBytId(){ Teacher teacher=teacherDao.findBytId(111111); System.out.println(teacher); } @Test public void testAddTeacher(){ java.util.Date d = new java.util.Date(); java.sql.Date date1 = new java.sql.Date(d.getTime()); Teacher teacher=new Teacher(); teacher.setDate1(date1); teacher.setIsHTeacher(1); teacher.setIsWork(1); teacher.setName("Amy"); teacher.settId("222222"); teacher.setUserName("user2"); teacherDao.addTeacher(teacher); } @Test public void testUpdateTeacher(){ Teacher teacher=new Teacher(); teacher.setIsWork(0); teacher.settId("222222"); teacherDao.updateTeacherIsWork(teacher); } @Test public void testdeleteTeacherById(){ teacherDao.deleteTeacherById("222222"); } @Test public void findAllTeacher(){ List<Teacher>list=teacherDao.findAllTeacher(); for (Teacher t:list ) { System.out.println(t); } } @After public void end(){ sqlSession.commit(); sqlSession.close(); } } ========================================================== MAPPER.XML ========================================================== <?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"> <mapper namespace="dao.TeacherDao"> <select id="findAllTeacher" resultType="entity.Teacher"> select * from teacher </select> <insert id="addTeacher" parameterType="entity.Teacher"> insert into teacher (isHTeacher,userName,name,tId,date1,isWork) values(#{isHTeacher},#{userName},#{name},#{tId},#{date1},#{isWork}) </insert> <delete id="deleteTeacherById" parameterType="String"> delete from teacher where tId=#{tId} </delete> <update id="updateTeacherIsWork" parameterType="entity.Teacher"> update teacher set isWork=#{isWork} where tId=#{tId} </update> <select id="findBytId" parameterType="int" resultType="entity.Teacher"> select * from teacher where tId=#{tId} </select> </mapper> ====================================================================== DAO (IMPL) ====================================================================== package dao; import entity.Teacher; import java.util.List; public interface TeacherDao { public List<Teacher> findAllTeacher(); public void addTeacher(Teacher teacher); public void deleteTeacherById(String id); public void updateTeacherIsWork(Teacher teacher); public Teacher findBytId(int id); }