create database mybatis-demo;
use mybatis-demo;
CREATE TABLE tb_user (
id char(32) NOT NULL,
user_name varchar(32) DEFAULT NULL,
password varchar(32) DEFAULT NULL,
name varchar(32) DEFAULT NULL,
age int(10) DEFAULT NULL,
sex char(2) DEFAULT NULL,
birthday date DEFAULT NULL,
created datetime DEFAULT NULL,
updated datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO tb_user
VALUES ('1' ,'zpc', '123456', '鹏程', 22, '男', '1990-09-02', sysdate(), sysdate());
INSERT INTO tb_user
VALUES ( '2','hj', '123456', '静静', 22, '女', '1993-09-05', sysdate(), sysdate());
单独使用
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>
</project>
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>
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/mybatis-demo"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</properties>
<environments default="test">
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis-demo"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
<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="mappers/UserDaoMapper.xml"/>
</mappers>
</configuration>
User.java
package entity;
import java.text.SimpleDateFormat;
import java.util.Date;
public class User {
private String id;
private String userName;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private String created;
private String updated;
public String getId() {
return id;
}
public void setId(String 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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
@Override
public String toString() {
return "entity.User{" +
"id='" + id + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", birthday='" + new SimpleDateFormat("yyyy-MM-dd").format(birthday) + '\'' +
", created='" + created + '\'' +
", updated='" + updated + '\'' +
'}';
}
}
UserDao.java
package dao;
import entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserDao {
/**
* 根据id查询用户信息
*
* @param id
* @return
*/
public User queryUserById(String id);
/**
* 查询所有用户信息
*
* @return
*/
public List<User> queryUserAll();
/**
* 新增用户
*
* @param user
*/
public void insertUser(User user);
/**
* 更新用户信息
*
* @param user
*/
public void updateUser(User user);
/**
* 根据id删除用户信息
*
* @param id
*/
public void deleteUser(String id);
}
UserDaoImpl.java
package dao.impl;
import dao.UserDao;
import entity.User;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class UserDaoImpl implements UserDao {
public SqlSession sqlSession;
public UserDaoImpl(SqlSession sqlSession){
this.sqlSession=sqlSession;
}
@Override
public User queryUserById(String id) {
return this.sqlSession.selectOne("UserDao.queryUserById",id);
}
@Override
public List<User> queryUserAll() {
return this.sqlSession.selectList("UserDao.queryUserAll");
}
@Override
public void insertUser(User user) {
this.sqlSession.insert("UserDao.insertUser", user);
}
@Override
public void updateUser(User user) {
this.sqlSession.update("UserDao.updateUser", user);
}
@Override
public void deleteUser(String id) {
this.sqlSession.delete("UserDao.deleteUser", id);
}
}
UserDaoMapper.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="UserDao">
<select id="queryUserById" resultType="entity.User">
select * from tb_user where id=#{id};
</select>
<select id="queryUserAll" resultType="entity.User">
select * from tb_user;
</select>
<insert id="insertUser" parameterType="entity.User">
INSERT INTO tb_user (
user_name,
password,
name,
age,
sex,
birthday,
created,
updated
)
VALUES
(
#{userName},
#{password},
#{name},
#{age},
#{sex},
#{birthday},
now(),
now()
);
</insert>
<update id="updateUser" parameterType="entity.User">
UPDATE tb_user
<trim prefix="set" suffixOverrides=",">
<if test="userName!=null">user_name = #{userName},</if>
<if test="password!=null">password = #{password},</if>
<if test="name!=null">name = #{name},</if>
<if test="age!=null">age = #{age},</if>
<if test="sex!=null">sex = #{sex},</if>
<if test="birthday!=null">birthday = #{birthday},</if>
updated = now(),
</trim>
WHERE
(id = #{id});
</update>
<delete id="deleteUser">
delete from tb_user where id=#{id}
</delete>
</mapper>
UserDaoTest.java
package dao;
import dao.impl.UserDaoImpl;
import entity.User;
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.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class UserDaoTest {
public UserDao userDao;
public SqlSession sqlSession;
@Before
public void setUp() throws Exception {
// mybatis-config.xml
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession
sqlSession = sqlSessionFactory.openSession();
this.userDao = new UserDaoImpl(sqlSession);
}
@Test
public void queryUserById() throws Exception {
System.out.println(this.userDao.queryUserById("1"));
}
@Test
public void queryUserAll() throws Exception {
List<User> userList = this.userDao.queryUserAll();
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void insertUser() throws Exception {
User user = new User();
user.setAge(16);
user.setBirthday(new Date("1990/09/02"));
user.setName("大鹏");
user.setPassword("123456");
user.setSex(1);
user.setUserName("evan");
this.userDao.insertUser(user);
this.sqlSession.commit();
}
@Test
public void updateUser() throws Exception {
User user = new User();
user.setBirthday(new Date());
user.setName("静鹏");
user.setPassword("654321");
user.setSex(1);
user.setUserName("evanjin");
user.setId("1");
this.userDao.updateUser(user);
this.sqlSession.commit();
}
@Test
public void deleteUser() throws Exception {
this.userDao.deleteUser("2");
this.sqlSession.commit();
}
}
与spring整合
- @Repository
- @Mapper