Mybatis学习——基本增删改查(CRUD)

时间:2023-03-16 18:40:50

Eclipse+Mybatis+MySql

  1.所需jar

Mybatis学习——基本增删改查(CRUD)

  2.项目目录

Mybatis学习——基本增删改查(CRUD)

  3.源代码

 package com.zhengbin.entity;

 public class Student {
private int id;
private String name;
private double score;
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Student(int id, String name, double score) {
super();
this.id = id;
this.name = name;
this.score = score;
}
// *注意这个必须加
public Student() {
super();
}
}

Student.java

 <?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.zhengbin.entity.studentMapper">
<!-- parameterType 参数表示需要参数的类型 -->
<!-- resultType 参数表示返回结果的类型,该可以写为实体包的全路径,或者在conf.xml配置文件中,声明实体的别名 -->
<select id="getStudent" parameterType="int" resultType="Student">
select * from student where id=#{id}
</select> <select id="getAllStudent" resultType="Student">
select * from student
</select> <insert id="addStudent" parameterType="Student">
insert into student(name,score) values(#{name},#{score})
</insert> <update id="updateStudent" parameterType="Student">
update student set name=#{name},score=#{score} where id=#{id}
</update> <delete id="deleteStudent" parameterType="int">
delete from student where id=#{id}
</delete>
</mapper>

studentMapper.xml

 package com.zhengbin.entity2;

 import org.apache.ibatis.annotations.Select;

 import com.zhengbin.entity.Student;

 public interface studentMapper {
@Select("select * from student where id=#{id}")
public Student testGet(int id);
}

studentMapper.java

 package com.zhengbin.test;

 import java.util.List;

 import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import com.zhengbin.entity.Student;
import com.zhengbin.util.MyBatisUtils; public class Test {
@org.junit.Test
public void testGet(){
SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
// 参数为TRUE,相当于session.commit();
SqlSession session = sessionFactory.openSession(true);
// 读取映射文件
String statement = "com.zhengbin.entity.studentMapper" + ".getStudent";
Student s = session.selectOne(statement,5);
System.out.println(s);
session.close();
} @org.junit.Test
public void testGetAll(){
SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
// 参数为TRUE,相当于session.commit();
SqlSession session = sessionFactory.openSession(true);
// 读取映射文件
String statement = "com.zhengbin.entity.studentMapper" + ".getAllStudent";
List<Student> list = session.selectList(statement);
System.out.println(list);
session.close();
} @org.junit.Test
public void testAdd(){
SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
SqlSession session = sessionFactory.openSession(true);
String statement = "com.zhengbin.entity.studentMapper" + ".addStudent";
Student s = new Student();
s.setName("zhengB");
s.setScore(95.9);
int insert = session.insert(statement, s);
System.out.println(insert);
session.close();
} @org.junit.Test
public void testUpdate(){
SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
SqlSession session = sessionFactory.openSession(true);
String statement = "com.zhengbin.entity.studentMapper" + ".updateStudent";
Student s = new Student();
s.setId(14);
s.setName("zhengbin");
s.setScore(96);
int update = session.update(statement, s);
System.out.println(update);
session.close();
} @org.junit.Test
public void testDelete(){
SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
SqlSession session = sessionFactory.openSession(true);
String statement = "com.zhengbin.entity.studentMapper" + ".deleteStudent";
int delete = session.delete(statement,21);
System.out.println(delete);
session.close();
}
}

Test.java

 package com.zhengbin.test;

 import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import com.zhengbin.entity.Student;
import com.zhengbin.entity2.studentMapper;
import com.zhengbin.util.MyBatisUtils; public class Test2 {
@org.junit.Test
public void testGet(){
SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
SqlSession session = sessionFactory.openSession(true);
studentMapper mapper = session.getMapper(studentMapper.class);
Student s = mapper.testGet(14);
System.out.println(s);
session.close();
}
}

Test2.java

 package com.zhengbin.util;

 import java.io.InputStream;

 import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtils {
public static SqlSessionFactory getFactory(){
String resource = "conf.xml";
InputStream is = MyBatisUtils.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
return sessionFactory;
}
}

MyBatisUtils.java

 <?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="jdbc.properties"/>
<!-- 取别名 -->
<typeAliases>
<!-- 方式一、为类取别名 -->
<!-- <typeAlias type="com.zhengbin.entity.Student" alias="_Student"/> -->
<!-- 方式二、自动以类名为别名 -->
<package name="com.zhengbin.entity"/>
</typeAliases>
<!--
development : 开发模式
work : 工作模式
-->
<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 resource="com/zhengbin/entity/studentMapper.xml"/>
<mapper class="com.zhengbin.entity2.studentMapper"/>
</mappers>
</configuration>

conf.xml

 driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3307/student
username=root
password=950906

jdbc.properties

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

log4j.xml

  4.遇到的问题

(1)奇怪的junit:如果新建一个class,名为Test则可能出现不能使用注解@Test的情况,此时用@org.junit.Test即可,或者更改class名,不以Test开头 好奇葩

(2)实体类必须要加superclass,否则报错,因为MyBatis无法通过配置文件找到实体类