SSM之Mybatis_ch4
XML映射文件细解(二)
- cache——命名空间的缓存配置
- cache-ref——引用其他命名空间的缓存配置
- resultMap——从数据库结果集中加载对象,是最复杂也最强大的元素
- sql——可被其他语句引用的可重用语句块
- insert——映射插入语句
- update——映射更新语句
- delete——映射删除语句
- select——映射查询语句
此篇只讲述CRUD的注解使用
CURD注解使用
使用注解后,就不用再新建UserMapper.xml
文件了。
// 查询所有用户
@Select("select * from mybatis.user")
List<User> getUserList();
// 通过id查询单个用户
// 通过@Param绑定参数,传递的参数名始终为@Param中的参数名
// 即User getUser(@Param("id") int XXX)也是只需要传递id参数即可,如删除操作示例参数
@Select("select * from mybatis.user where id=#{id}")
User getUser(@Param("id") int id);
// 增
@Insert("insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})")
boolean insertUser(User user);
// 改
@Update("update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}")
boolean updateUser(User user);
// 删
// 使用@Param时会优先使用其中的参数
@Delete("delete from mybatis.user where id=#{id}")
boolean deleteUser(@Param("id") int xxx);
在mybatis-config.xml
文件中引入mapper方式也需要有所改变
直接使用引入Usermapper
类即可。
<mappers>
<!--绑定接口必须使用此方法,即用class-->
<mapper class="com.reflect.mapper.UserMapper"/>
</mappers>
全部代码
项目结构图
1.新建User.java
package com.reflect.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* author: Administrator
* date: 2021/1/1 - 14:46
*/
// 此处为演示注解开发,使用了Lombok注解作为实验。
// 如果也想运行此代码,请在IDEA中导入Lombok的Maven依赖以及下载Lombok插件
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
private int id;
private String name;
private String pwd;
}
2.新建UserMapper.java
package com.reflect.mapper;
import com.reflect.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* author: Administrator
* date: 2021/1/1 - 14:50
*/
public interface UserMapper {
// 查询所有用户
@Select("select * from mybatis.user")
List<User> getUserList();
// 通过id查询单个用户
// 通过@Param绑定参数,传递的参数名始终为@Param中的参数名
// 即User getUser(@Param("id") int XXX)也是只需要传递id参数即可,如删除操作示例参数
@Select("select * from mybatis.user where id=#{id}")
User getUser(@Param("id") int id);
// 增
@Insert("insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})")
boolean insertUser(User user);
// 改
@Update("update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}")
boolean updateUser(User user);
// 删
// 使用@Param时会优先使用其中的参数
@Delete("delete from mybatis.user where id=#{id}")
boolean deleteUser(@Param("id") int xxx);
}
3.新建MybatisUtils.java
package com.reflect.utils;
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.InputStream;
/**
* author: Administrator
* date: 2021/1/1 - 15:03
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
4.新建`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 resource="dbconfig.properties">
</properties>
<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>
<!-- 绑定接口必须使用此方法,即用class-->
<mapper class="com.reflect.mapper.UserMapper"/>
</mappers>
</configuration>
5.新建`dbconfig.properties
driver=com.mysql.cj.jdbc.Driver
#url中&在配置文件可以直接写,但是在程序中需要进行可能转义
url=jdbc:mysql://192.168.199.131:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
6.新建Test类进行测试
import com.reflect.mapper.UserMapper;
import com.reflect.pojo.User;
import com.reflect.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
import java.util.UUID;
/**
* author: Administrator
* date: 2021/1/1 - 15:11
*/
public class MyTest {
@Test
public void getUserList() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
@Test
public void getUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUser(1);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
@Test
public void insertUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
int id = (int) (Math.random()*1000000000);
String string = UUID.randomUUID().toString();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
boolean res = mapper.insertUser(new User(id, string, "pwd" + string));
if (res) {
System.out.println("插入成功!!!");
}
// 提交事务!!!
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
@Test
public void updateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
String string = UUID.randomUUID().toString();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
boolean res = mapper.updateUser(new User(362303348, string, "pwd" + string));
if (res) {
System.out.println("修改成功!!!");
}
// 提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
@Test
public void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
boolean res = mapper.deleteUser(492496192);
if (res) {
System.out.println("删除成功!!!");
}
// 提交事务!!!
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
}