项目框架
pom.xml导入各种依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
resources中写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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/my2?useSSl=true&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="A.Mapper"/>
</mappers>
</configuration>
A包中:
类:
User:实体类
package A;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookId;
private String bookName;
private String bookCounts;
}
MybatisUtils:MyBatis工具实现类
package A;
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.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
System.out.println("错误");
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
可以直接用,这个类基本不会变。
接口:
Mapper:写要用到的方法,在其上方用注解实现数据库的语句
package A;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;
public interface Mapper{
//查询全部用户
@Select("select * from user")
List<User> getUserList();
@Select("select * from user where name like #{value}")
List<User> getUserLike(String value);
//根据ID查询用户
@Select("select * from user where id=#{id}")
User getUserById(int id);
//增加一个用户
@Insert("insert into user values (#{id},#{name},#{pwd})")
int addUser(User user);
//万能的Map
@Insert("insert into user(id,name) values (#{id},#{name})")
int addUser1(@Param("id") int id,@Param("name") String name);
//修改用户
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
//删除用户
@Delete("delete from user where id=#{id} and name=#{name}")
int deleteUser(@Param("id") int id, @Param("name") String name);
}
注意要把这个配置到MyBatis配置文件中
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
放置在MyBatis配置文件中,具体位置请看resources中
Test包:
Test类:测试类
import A.Mapper;
import A.MybatisUtils;
import A.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Text {
@Test
public void test(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
Mapper mapper= (Mapper) sqlSession.getMapper(Mapper.class);
List<User> list=mapper.getUserList();
for (User user : list) {
System.out.println(user);
}
}
@Test
public void test1(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
Mapper mapper=sqlSession.getMapper(Mapper.class);
User user=mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void test2(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
Mapper mapper=sqlSession.getMapper(Mapper.class);
int res=mapper.addUser(new User(5,"张三","1234"));
if(res>0) {
System.out.print("插入成功");
sqlSession.commit(); //提交事务
}
sqlSession.close();
}
@Test
public void test3(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
Mapper mapper=sqlSession.getMapper(Mapper.class);
int res=mapper.updateUser(new User(2,"张三","1234"));
if(res>0) {
System.out.print("修改成功");
sqlSession.commit(); //提交事务
}
sqlSession.close();
}
@Test
public void test4(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
Mapper mapper=sqlSession.getMapper(Mapper.class);
int res=mapper.deleteUser( 2,"张三");
if(res>0) {
System.out.print("删除成功");
sqlSession.commit(); //提交事务
}
sqlSession.close();
}
@Test
public void test5(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
Mapper mapper= (Mapper) sqlSession.getMapper(Mapper.class);
List <User> list=mapper.getUserLike("张%");
for (User user : list) {
System.out.println(user);
}
}
}
数据库中表的创建
CREATE TABLE `user` (
`id` INT NOT NULL ,
`name` VARCHAR(40) DEFAULT NULL,
`pwd` VARCHAR(40) DEFAULT NULL,
PRIMARY KEY(id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
程序运行图
查询所有用户