Mysql建表语句:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`state` tinyint(4) DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
创建Maven项目
项目目录结构如下:
导入项目依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
编写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">
<!--mybatis 核心配置文件-->
<configuration>
<!--引入外部properties文件 -->
<properties resource="mysql.properties"></properties>
<settings>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<environments default="development">
<environment id="development">
<!--默认使用JDBC事务管理-->
<transactionManager type="JDBC"/>
<!--配置数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_user?useSSL=false&userUnicode=true&characterEncoding=UTF-8&serverTimezone=CST"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/mapper/UserMapper.xml"/>
</mappers>
</configuration>
创建Mybatis的工具类用于获取 SqlSession对数据库进行操作
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.Reader;
/**
* @author kate
*/
public class MyBatisUtil {
private static String CONFIG_FILE_LOCATION = "mybatis-coonfig.xml";
private static final ThreadLocal<SqlSession> threadLocal = new
ThreadLocal<SqlSession>();
private static SqlSessionFactory sessionFactory;
static {
try {
Reader reader= Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
sessionFactory=builder.build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
SqlSession session = threadLocal.get();
if (session == null) {
session = (sessionFactory!=null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void closeSession() {
SqlSession session = threadLocal.get();
if (session != null) {
session.close();
threadLocal.set(null);
}
}
}
创建对应mysql数据库表的实体类:
package com.mybatis.bean;
import lombok.*;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
public class User implements Serializable {
private int id;
private String name;
private String password;
private int age;
private int state;
}
编写*Mapper.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="com.mybatis.dao.UserMapper">
<select id="queryUserById" resultType="com.mybatis.bean.User" parameterType="int">
select * from user where id = #{id}
</select>
<insert id="insert" parameterType="com.mybatis.bean.User">
insert into user ( name, password,age,state )
values (#{name}, #{password},#{age},#{state} )
</insert>
<select id="getAll" resultType="com.mybatis.bean.User">
select * from user ;
</select>
<update id="updateUserById" parameterType="com.mybatis.bean.User">
update user set name =#{name},password=#{password},age=#{age},state=#{state} where id=#{id}
</update>
<delete id="deleteUserById" parameterType="int" >
delete from user where id=#{id}
</delete>
<select id="getAllLikeName" resultType="com.mybatis.bean.User" parameterType="map">
select * from user where name like #{name}
</select>
<select id="queryUserById2" resultType="com.mybatis.bean.User" parameterType="map">
select * from user where id = #{stuid}
</select>
</mapper>
创建对应的接口:
package com.mybatis.dao;
import com.mybatis.bean.User;
import java.util.List;
/**
* @author kate
*/
public interface UserMapper {
User queryUserById(int id);
int insert(User user);
List<User> getAll();
int updateUserById(User user);
int deleteUserById(int id);
User queryUserById2(Map<String, Object> map);
List<User> getAllLikeName(Map<String, Object> map);
}
测试
package com.mybatis;
import com.mybatis.bean.User;
import com.mybatis.dao.UserMapper;
import com.mybatis.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MybatisTest {
private SqlSession session;
private UserMapper mapper;
@Before
public void before() {
session = MyBatisUtil.getSession();
mapper = session.getMapper(UserMapper.class);
}
@After
public void after() {
session.commit();
}
@Test
public void queryUserById() {
User user = mapper.queryUserById(1);
System.out.println(user.toString());
}
@Test
public void insert() {
User user = new User();
user.setName("李华");
user.setPassword("123456");
user.setAge(22);
user.setState(1);
int res = mapper.insert(user);
System.out.println(res);
}
@Test
public void getAll() {
for (User user : mapper.getAll()) {
System.out.println(user);
}
}
@Test
public void updateUserById(){
User user = new User();
user.setId(2);
user.setName("hahaha");
user.setPassword("1234");
user.setAge(20);
user.setState(0);
int i = mapper.updateUserById(user);
if (i==1) {
System.out.println("更新数据成功!");
} else {
System.out.println("更新数据失败!");
}
}
@Test
public void deleteUserById(){
int i = mapper.deleteUserById(2);
if (i==1) {
System.out.println("删除数据成功!");
} else {
System.out.println("删除数据失败!");
}
}
}
//Map扩展
@Test
public void getAllLikeName() {
Map<String, Object> map = new HashMap<>();
map.put("name", "%" + "zhang" + "%");
List<User> users = mapper.getAllLikeName(map);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void queryUserById2(){
Map<String, Object> map = new HashMap<>();
map.put("stuid", 1);
User user = mapper.queryUserById2(map);
System.out.println(user);
}