Mybatis入门之增删改查(CRUD)
程序员文章站
2022-05-23 19:45:47
...
整体代码架构
项目代码下载
使用Mybatis,需要导入 mybatis-3.2.7.jar mysql-jdbc.jar
数据库
CREATE DATABASE `mybatis` ;
USE `mybatis`;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
insert into `users`(`id`,`NAME`,`age`) values (1,'阿星',11),(2,'阿黄',27),(3,'阿华',23);
配置文件 mybatis.conf.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>
<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://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/mapping/userMapper.xml"/>
</mappers>
</configuration>
service 具体实现增删改查
package com.mybatis.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.mybatis.bean.User;
import com.mybatis.utils.DbUtils;
public class UserService {
public static SqlSession getSession(){
return DbUtils.getSession();
}
public static void getUserById(int id){
String statement = "com.mybatis.mapping.userMapper.getUser";
System.out.println("select");
User user = getSession().selectOne(statement,id);
System.out.println(user);
}
public static void getUserAll(){
String statement = "com.mybatis.mapping.userMapper.getUserAll";
List<User> list = getSession().selectList(statement);
System.out.println(list.toString());
}
public static User getLastUser(){
String statement = "com.mybatis.mapping.userMapper.getLastUser";
User user = getSession().selectOne(statement);
//System.out.println(list.toString());
System.out.println(user);
// return list.get(0);
return user;
}
public static void update(User user){
System.out.println("update "+user.toString());
String statement = "com.mybatis.mapping.userMapper.updateUser";
getSession().update(statement, user);
}
public static void delUserById(int id){
System.out.println("del id ="+id);
String statement = "com.mybatis.mapping.userMapper.deleteUser";
getSession().delete(statement, id);
}
public static void insertUser(User user){
String statement = "com.mybatis.mapping.userMapper.insertUser";
getSession().insert(statement, user);
}
}
数据库连接
package com.mybatis.utils;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.mybatis.test.Test;
public class DbUtils {
private static SqlSessionFactory sessionFactory;
static {
try{
String resource = "mybatis.conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(is);
}catch(Exception e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sessionFactory.openSession();
}
}
测试增删改查
package com.mybatis.test;
import java.io.IOException;
import com.mybatis.bean.User;
import com.mybatis.service.UserService;
public class Test {
public static void main(String[] args) throws IOException {
//insert
User userAdd = new User();
userAdd.setAge(50);
userAdd.setName("阿华");
UserService.insertUser(userAdd);
//select
UserService.getUserById(1);
UserService.getUserAll();
//update
User userUpdate = UserService.getLastUser();
userUpdate.setName("阿星");
userUpdate.setAge(11);
UserService.update(userUpdate);
//delete
User userDel = UserService.getLastUser();
UserService.delUserById(userDel.getId());
UserService.getLastUser();
}
}
xml mapping
<?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.mapping.userMapper" >
<select id="getUser" parameterType="int" resultType="com.mybatis.bean.User">
select * from users where id=#{id}
</select>
<select id="getUserAll" resultType="com.mybatis.bean.User">
SELECT * FROM users
</select>
<select id="getLastUser" resultType="com.mybatis.bean.User">
SELECT * FROM users ORDER BY id DESC LIMIT 1
</select>
<update id="updateUser" parameterType="com.mybatis.bean.User">
UPDATE users SET NAME = #{name}, age = #{age} WHERE id = #{id};
</update>
<insert id="insertUser" parameterType="com.mybatis.bean.User">
INSERT INTO users (id, NAME, age) VALUES (#{id}, #{name}, #{age}) ;
</insert>
<delete id="deleteUser" parameterType="int">
DELETE
FROM
users
WHERE id = #{id} ;
</delete>
</mapper>
实体类
package com.mybatis.bean;
public class User {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User bean {id=" + id + ", name=" + name + ", age=" + age + "}";
}
}
上一篇: 13种排序算法详解
推荐阅读
-
idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD
-
Mybatis框架学习之增删改查
-
MyBatis从入门到精通(四):MyBatis XML方式的基本用法之增删改
-
小白入门:mybatis超简单方便的增删改查操作(idea2019)
-
Mybatis入门教程,实现数据库简单增删改查
-
Mybatis快速入门增删改查
-
JAVAWEB开发之mybatis详解(一)——mybatis的入门(实现增删改查操作)、自定义别名、抽取代码块以及动态SQL的使用
-
Mybatis入门之增删改查(CRUD)
-
idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD
-
ElasticSearch入门-增删改查(CRUD)