Mybatis实现数据的增删改查实例(CRUD)

网友投稿 234 2023-05-15


Mybatis实现数据的增删改查实例(CRUD)

什么是 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

"http://mybatis.org/dtd/mybatis-3-config.dtd">

定义User mappers的User.xml配置文件

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from `user` where user.id = #{id}

select * from user where user.userName = #{userName}

useGeneratedKeys="true" keyProperty="id">

insert into user(userName,userAge,userAddress)

values(#{userName},#{userAge},#{userAddress})

useGeneratedKeys="true" keyProperty="id">

insert into user(userName,userAge,userAddress)

values(#{userName},#{userAge},#{userAddress})

update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}

delete from user where id=#{id}

配置文件实现了接口和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 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 getoPDzDSession() {

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 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());

}

}

}

代码下载:MyBaitsSimpleDemo_jb51.rar


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:关于bootstrap日期转化,bootstrap
下一篇:基于angular实现三级联动的生日插件
相关文章

 发表评论

暂时没有评论,来抢沙发吧~