Mybatis实现增删改查(CRUD)实例代码

作者:阿凡卢 时间:2022-10-05 20:03:22 

MyBatis简介

MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

MyBatis下载:https://github.com/mybatis/mybatis-3/releases

Mybatis实例

对一个User表的CRUD操作:

User表:


-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userAge` int(11) DEFAULT NULL,
`userAddress` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');

在Src目录下建一个mybatis的xml配置文件Configuration.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>
<!-- mybatis别名定义 -->
<typeAliases>
<typeAlias alias="User" type="com.mybatis.test.User"/>
</typeAliases>
<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://127.0.0.1:3306/mybatis" />
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<!-- mybatis的mapper文件,每个xml配置文件对应一个接口 -->
<mappers>
<mapper resource="com/mybatis/test/User.xml"/>
</mappers>
</configuration>

定义User mappers的User.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.test.IUserOperation">
<!-- select语句 -->
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where user.id = #{id}
</select>
<!-- 定义的resultMap,可以解决类的属性名和数据库列名不一致的问题-->
<!-- <resultMap type="User" id="userResultMap">
<id property="id" column="user_id" />
<result property="userName" column="user_userName" />
<result property="userAge" column="user_userAge" />
<result property="userAddress" column="user_userAddress" />
</resultMap> -->
<!-- 返回list的select语句,注意 resultMap的值是指向前面定义好的 -->
<!-- <select id="selectUsersByName" parameterType="string" resultMap="userResultMap">
select * from user where user.userName = #{userName}
</select> -->
<select id="selectUsersByName" parameterType="string" resultType="User">
select * from user where user.userName = #{userName}
</select>
<!--执行增加操作的SQL语句。id和parameterType分别与IUserOperation接口中的addUser方法的名字和参数类型一致。
useGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键;keyProperty="id"指定把获取到的主键值注入到User的id属性-->
<insert id="addUser" parameterType="User"
useGeneratedKeys="true" keyProperty="id">
insert into user(userName,userAge,userAddress)
values(#{userName},#{userAge},#{userAddress})
</insert>
<update id="updateUser" parameterType="User" >
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>

配置文件实现了接口和SQL语句的映射关系。selectUsersByName采用了2种方式实现,注释掉的也是一种实现,采用resultMap可以把属性和数据库列名映射关系定义好,property为类的属性,column是表的列名,也可以是表列名的别名!

User类的定义:


package com.mybatis.test;
public class User {
private int id;
private String userName;
private int userAge;
private String userAddress;
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 int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
@Override
public String toString(){
return this.userName+" "+this.userAge+" "+this.userAddress;
}
}

IUserOperaton定义:


package com.mybatis.test;
import java.util.List;
public interface IUserOperation {
public User selectUserByID(int id);
public List<User> selectUsersByName(String userName);
public void addUser(User user);
public void updateUser(User user);
public void deleteUser(int id);
}

IUserOperation为操作接口,函数名和mybatis的xml配置文件中的操作id名对应。

测试类Test:


package com.mybatis.test;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public void getUserByID(int userID) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
User user = userOperation.selectUserByID(userID);
if (user != null) {
System.out.println(user.getId() + ":" + user.getUserName()
+ ":" + user.getUserAddress());
}
} finally {
session.close();
}
}
public void getUserList(String userName) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
List<User> users = userOperation.selectUsersByName(userName);
for (User user : users) {
System.out.println(user.getId() + ":" + user.getUserName()
+ ":" + user.getUserAddress());
}
} finally {
session.close();
}
}
/**
* 增加后要commit
*/
public void addUser() {
User user = new User();
user.setUserAddress("place");
user.setUserName("test_add");
user.setUserAge(30);
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
userOperation.addUser(user);
session.commit();
System.out.println("新增用户ID:" + user.getId());
} finally {
session.close();
}
}
/**
* 修改后要commit
*/
public void updateUser() {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
User user = userOperation.selectUserByID(1);
if (user != null) {
user.setUserAddress("A new place");
userOperation.updateUser(user);
session.commit();
}
} finally {
session.close();
}
}
/**
* 删除后要commit.
*
* @param id
*/
public void deleteUser(int id) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
userOperation.deleteUser(id);
session.commit();
} finally {
session.close();
}
}
public static void main(String[] args) {
try {
Test test = new Test();
// test.getUserByID(1);
// test.getUserList("test1");
// test.addUser();
// test.updateUser();
// test.deleteUser(6);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

以上所述是小编给大家介绍的Mybatis实现增删改查(CRUD)实例代码 网站的支持!

标签:mybatis,增删,改查,crud
0
投稿

猜你喜欢

  • Java集合框架之Stack Queue Deque使用详解刨析

    2022-06-11 06:10:19
  • Java Mybatis批量修改封装详解

    2021-12-29 22:41:52
  • Android开发实现的ViewPager引导页功能(动态加载指示器)详解

    2021-10-16 17:40:35
  • @GrpcServise 注解的作用和使用示例详解

    2021-07-25 21:12:25
  • 一篇文章带你入门Java修饰符

    2021-12-25 12:46:01
  • 使用JMF实现java视频播放器

    2022-12-26 00:28:25
  • Kotlin协程Dispatchers原理示例详解

    2022-09-26 00:09:45
  • C#实现查杀本地与远程进程的方法

    2023-08-10 08:01:30
  • 一篇文章带你了解java接口与继承

    2022-07-15 02:44:08
  • mybatis-plus配置控制台打印完整带参数SQL语句的实现

    2023-11-24 22:43:58
  • java 引用传递的三种类型小结

    2023-09-03 03:59:47
  • C#读写文件的方法汇总

    2022-03-01 04:41:41
  • Java中this关键字的用法详解

    2023-10-04 05:05:53
  • Android虚拟机Dalvik和ART科普

    2022-12-31 06:02:28
  • 改进c# 代码的五个技巧(一)

    2021-07-17 23:49:30
  • Java调用shell脚本解决传参和权限问题的方法

    2023-04-27 05:50:37
  • C# 一个WCF简单实例

    2023-07-12 20:53:43
  • springboot post接口接受json时,转换为对象时,属性都为null的解决

    2023-06-17 15:24:23
  • Java经典面试题最全汇总208道(三)

    2023-11-15 23:30:42
  • 深入理解C#中的枚举

    2022-06-03 02:58:34
  • asp之家 软件编程 m.aspxhome.com