数据持久化就是将内存中的数据模型转换为存储模型,以及将存储模型转换为内存中的数据模型的统称
存储模型可以是:关系模型、XML、二进制流等等
在Java程序中最普遍的例子就是:
Java的MVC三层架构:
持久层框架:Hibernate、MyBatis
MyBatis帮助程序员将数据存入到数据库中:
我们的需求是实现对用户表(User)的增、删、改、查操作。
步骤:搭建环境–>导入Mybatis–>编写代码–>测试!
1.搭建数据库:
创建一个mysql数据库(mybatis),创建用户表(user)
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),
(2,'李四','111111'),
(3,'王五','654321')
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
package com.mybatis.util;
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 MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
package com.mybatis.vo;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
package com.mybatis.mapper;
import com.mybatis.vo.User;
import java.util.List;
public interface UserMapper {
//方法返回值根据JDBC中执行对应的sql语句返回值进行判断
int insertUser(User user);//增添用户
int deleteUser(int id);//删除用户
int updateUser(User user);//修改用户
List<User> getUserList();//查询用户列表
User getUserById(int id);//根据id查询用户
}
<mapper namespace="com.mybatis.mapper.UserMapper">
<insert id="insertUser" parameterType="com.mybatis.vo.User">
insert into mybatis.user (id,username,password) values (#{id},#{username},#{password})
insert>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=${id}
delete>
<update id="updateUser" parameterType="com.mybatis.vo.User">
update mybatis.user set username=#{username},password=#{password} where id=#{id}
update>
<select id="getUserList" resultType="com.mybatis.vo.User">
select * from mybatis.user
select>
<select id="getUserById" parameterType="int" resultType="com.mybatis.vo.User">
select * from mybatis.user where id=#{id}
select>
mapper>
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/mybatis/mapper/UserMapper.xml"/>
mappers>
configuration>
实现接口方法前,我们需要通过工具类得到sqlSession对象,并通过其getMapper(Mapper接口class文件)
获取接口对象来调用其方法。(再操作数据库进行增删改后必须通过sqlSession.commit()
提交事务才能执行成功)
创建一个User类对象,并给成员变量赋值,再传入接口中增添用户的方法执行:
@org.junit.Test
public void insertUser(){
User user = new User();
user.setId(4);
user.setUsername("赵六");
user.setPassword("222222");
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.insertUser(user);
sqlSession.commit();
System.out.println(i);
}
通过传入参数id,执行接口中删除指定用户的方法:
@org.junit.Test
public void deleteUser(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(2);
sqlSession.commit();
System.out.println(i);
}
创建一个User类对象,并给成员变量赋值,再传入接口中修改用户的方法执行:
@org.junit.Test
public void updateUser(){
User user = new User();
user.setId(1);
user.setUsername("李雷");
user.setPassword("000000");
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.updateUser(user);
sqlSession.commit();
System.out.println(i);
}
直接执行接口中查询用户列表的方法,返回List集合:
@org.junit.Test
public void getUserList(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
通过传入参数id,执行接口中根据id查询用户的方法:
@org.junit.Test
public void getUserById(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User id1 = mapper.getUserById(1);
System.out.println("id为1的用户:"+id1);
User id3 = mapper.getUserById(3);
System.out.println("id为3的用户:"+id3);
User id4 = mapper.getUserById(4);
System.out.println("id为3的用户:"+id4);
}
返回指定id的User对象: