此两种方法都是基于maven项目的基础上运行
主要步骤如下:
1、在mevan中的pom文件添加依赖文件:
2、在src目录下编写编写配置文件(mybatis-cfg.xml)
3、编写实体类(Student.java)
4、编写映射文件(StudentMapper.xml)
5、编写测试文件
6、调用JUnit 5进行调试
核心文件含义:
(1)mybatis-config.xml是Mybatis的核心配置文件,通过其中的配置可以生成SqlSessionFactory,也就是SqlSession工厂
(2)基于SqlSessionFactory可以生成SqlSession对象
(3)SqlSession是一个既可以发送SQL去执行,并返回结果,类似于JDBC中的Connection对象,也是Mybatis中至关重要的一个对象。
(4)Executor是SqlSession底层的对象,用于执行SQL语句
(5)MapperStatement对象也是SqlSession底层的对象,用于接收输入映射(SQL语句中的参数),以及做输出映射(即将SQL查询的结果映射成相应的结果)
pom文件所需添加的依赖:
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version> 1.2.12 </version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.example</groupId> <artifactId>javaTest</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
一、配置日志文件代码(可要可不要):
log4j.rootLogger=debug, stdout,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
Log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
Log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
Log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
二、核心配置文件代码:
<?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="develop">
<environment id="develop">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/xsgl?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentMapper.xml"/>//第一种:映射文件的地址
<mapper class="com.jiazhong.Dao.StudentDao"/>//dao的接口位置
</mappers>
</configuration>
三、1.第一种方法:
映射文件代码:
<?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="StudentMapper">
<select id="findAll" resultType="com.jiazhong.pojo.Student">//javabean的地址,查询必须有
select * from student//sql语句
</select>
<update id="insert">//添加
insert into student values(null,"bb","男",22,"dd","2024-7-7")
</update>
<delete id="delete">//删除
delete from student where id="19"
</delete>
<update id="update">//更新
update student set name="aa",sex="bb",age=33,major="dd",time="2024-7-11" where id=25;
</update>//根据id查找
<select id="findById" resultType="com.jiazhong.pojo.Student">
select * from student where id=#{id}
</select>
<update id="insertData">//动态插入
insert into student values(null,#{name},#{sex},#{age},#{major},#{time})
</update>
<update id="updateData">//动态更新
update student set name=#{name},sex=#{sex},age=#{age},major=#{major},time=#{time} where id=#{id};
</update>
<delete id="deleteData">//动态删除
delete from student where id=#{id}
</delete>
<select id="findAll1" resultType="com.jiazhong.pojo.Student">//查询一列
select ${cols} from student
</select>
<select id="findAll2" resultType="com.jiazhong.pojo.Student">//模糊查询
select * from student where name like"%${name}%"
</select>
<select id="findAllAge" resultType="com.jiazhong.pojo.Student">//条件查询
select * from student where 1=1
<if test="minAge !=null">
and age>#{minAge}
</if>
<if test="maxAge !=null">
and age<![CDATA[<]]>#{maxAge}
</if>
</select>
<select id="deleteByIds">
delete from student where id in
<foreach collection="array" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</select>
</mapper>
测试代码:
import com.jiazhong.pojo.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.apache.log4j.PropertyConfigurator;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
public class TestMybits {
/**
* 找所用数据
* @throws IOException
*/
@Test
public void findAll() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
List<Student> students = sqlSession.selectList("StudentMapper.findAll");
for (Student stu:students){
System.out.println("信息:" + stu);
}
}
/**
* 配置文件封装
* @throws IOException
*/
public static void info() throws IOException {
Properties properties = new Properties();
FileInputStream fileInputStream = new FileInputStream("src/main/resources/config/log4j.properties");
properties.load(fileInputStream);
PropertyConfigurator.configure(properties);
}
/**
* 添加一条数据
* @throws IOException
*/
@Test
public void insert() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
int update= sqlSession.update("StudentMapper.insert");
sqlSession.commit();
System.out.println("update = " + update);
}
/**
* 删除一条数据
* @throws IOException
*/
@Test
public void delete() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
int update= sqlSession.update("StudentMapper.delete");
sqlSession.commit();
System.out.println("update = " + update);
}
/**
* 更新一条数据
* @throws IOException
*/
@Test
public void update() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
int update= sqlSession.update("StudentMapper.update");
sqlSession.commit();
System.out.println("update = " + update);
}
/**
* 根据id查数据
* @throws IOException
*/
@Test
public void findById() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
List<Student> student = sqlSession.selectList("StudentMapper.findById",25);
System.out.println("student = " + student);
}
/**
* 添加数据传值
* @throws IOException
*/
@Test
public void insertData() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
HashMap map=new HashMap();
map.put("name","aa");
map.put("sex","bb");
map.put("age",33);
map.put("major","ee");
map.put("time","2024-8-8");
int update= sqlSession.update("StudentMapper.insertData",map);
sqlSession.commit();
System.out.println("update = " + update);
}
/**
* 更新数据传值
* @throws IOException
*/
@Test
public void updateData() throws IOException {
Student student = new Student();
student.setName("bb");
student.setSex("vv");
student.setAge(33);
student.setMajor("ff");
student.setTime("2024-8-9");
student.setId(29);
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
int update= sqlSession.update("StudentMapper.updateData",student);
sqlSession.commit();
System.out.println("update = " + update);
}
/**
* 删除数据传值
* @throws IOException
*/
@Test
public void deleteData() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
int update= sqlSession.update("StudentMapper.deleteData",28);
sqlSession.commit();
System.out.println("update = " + update);
}
@Test
public void findAll1() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
HashMap map = new HashMap();
map.put("cols","name,sex");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
List<Student> students = sqlSession.selectList("StudentMapper.findAll1",map);
for (Student stu:students){
System.out.println("信息:" + stu);
}
}
@Test
public void findAll2() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
HashMap map = new HashMap();
map.put("name","bb");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
List<Student> students = sqlSession.selectList("StudentMapper.findAll2",map);
for (Student stu:students){
System.out.println("信息:" + stu);
}
}
@Test
public void findAllAge() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
HashMap<String, Object> map = new HashMap<>();
map.put("minAge",10);
map.put("maxAge",30);
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
List<Student> students = sqlSession.selectList("StudentMapper.findAllAge",map);
for (Student stu:students){
System.out.println("信息:" + stu);
}
}
@Test
public void deleteByIds() throws IOException {
TestMybits.info();
InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
//获取一个工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//通过工厂获取一个对象
SqlSession sqlSession = build.openSession();
Integer [] ids={17,18,24};
int delete= sqlSession.delete("StudentMapper.deleteByIds",ids);
sqlSession.commit();
System.out.println("delete = " + delete);
}
public static void main(String[] args) throws IOException {
TestMybits testMybits = new TestMybits();
// testMybits.findAll();
testMybits.insert();
}
}
2.第二种:注解的方法连接数据库进行增删查改
接口代码:
import com.jiazhong.pojo.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface StudentDao {
@Select("select * from student")//sql语句
List<Student> findAll();
@Insert("insert into student values(null,#{name},#{sex},#{age},#{major},#{time})")
void saveStudent(Student student);
@Delete("delete from student where id=#{id}")
void deleteStudent(int id);
@Update("update student set name=#{name},sex=#{sex},age=#{age},major=#{major},time=#{time}where id=#{id}")
void updateStudent(Student student);
@Select("select * from student where id=#{id}")
Student selectById(int id);
@Select("select * from student where name like '%${value}%'")
List<Student> selectByName(String name);
@Select("select count(*) from student")
int selectTotal();
// @Select("select * from user where sname=#{sname} and password=#{password}")
// User login(@Param("sname") String sname,@Param("password") String password);
}
测试代码:
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private String major;
private String time;
public Student() {
}
public Student(Integer id, String name, String sex, Integer age, String major, String time) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.major = major;
this.time = time;
}
/**
* 获取
* @return id
*/
public Integer getId() {
return id;
}
/**
* 设置
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return sex
*/
public String getSex() {
return sex;
}
/**
* 设置
* @param sex
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* 获取
* @return age
*/
public Integer getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(Integer age) {
this.age = age;
}
/**
* 获取
* @return major
*/
public String getMajor() {
return major;
}
/**
* 设置
* @param major
*/
public void setMajor(String major) {
this.major = major;
}
/**
* 获取
* @return time
*/
public String getTime() {
return time;
}
/**
* 设置
* @param time
*/
public void setTime(String time) {
this.time = time;
}
public String toString() {
return "Stusent{id = " + id + ", name = " + name + ", sex = " + sex + ", age = " + age + ", major = " + major + ", time = " + time + "}";
}
标签:改查,update,public,增删,sqlSession,build,student,mybatis,id
From: https://blog.csdn.net/2301_76908023/article/details/140769213