在初识Mybatis后,对于数据库的操作无异于增删改查的操作,今天就来发一下对于用户表最最最最基本的增删改查操作,有基础才能攀登,搞搞搞!!
数据库表
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 50721
Source Host : localhost:3306
Source Schema : mybatis_test
Target Server Type : MySQL
Target Server Version : 50721
File Encoding : 65001
Date: 31/12/2020 14:48:07
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(120) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gender` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`email` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`province` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`city` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`birthday` date NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (2, '王小蓝', '222', '男', '222@qq.com', '辽宁省', '沈阳市', '2020-12-29');
INSERT INTO `user` VALUES (3, '王晨', '333', '男', '333@qq.com', '黑龙江省', '哈尔滨市', '2020-12-27');
INSERT INTO `user` VALUES (4, '王丽', '444', '女', '444@qq.com', '吉林省', '通辽市', '2020-12-02');
INSERT INTO `user` VALUES (5, '王晨光', '1222', '男', '1289418375@qq.com', '辽宁省', '大连市', '1999-12-22');
INSERT INTO `user` VALUES (6, '王小白', '122', '男', '1289418375@qq.com', '辽宁省', '大连市', '1999-12-22');
SET FOREIGN_KEY_CHECKS = 1;
大家用自己的可视化数据库软件运行以下就可以了,本小白用的是navicat,在构建完表后,就该用我们高大上的mybatis来进行操作了
项目配置可见上一篇博文王小白初识Mybaits
下面就直接为大家送上代码了 gogogo!!!
首先要创建一个实体类UserBean
package javabean;
import java.util.Date;
public class UserBean {
private int id;
private String username;
private String password;
private String gender;
private String email;
private String province;
private String city;
private Date birthday;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public UserBean() {
super();
// TODO Auto-generated constructor stub
}
public UserBean(int id, String username, String password, String gender, String email, String province, String city,
Date birthday) {
super();
this.id = id;
this.username = username;
this.password = password;
this.gender = gender;
this.email = email;
this.province = province;
this.city = city;
this.birthday = birthday;
}
}
不会真的还有人认为我怎么辛苦就写了get/set吧 你们的编译器有自动生成功能千万别忘了哦!!!
第二连接数据库
package datasource;
import java.io.IOException;
import java.io.InputStream;
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 DataConnection {
private String resource="SqlMapConfig.xml";
private SqlSessionFactory sessionFactory;
private SqlSession sqlSession;
public SqlSession getSqlSession() throws IOException {
InputStream inputStream=Resources.getResourceAsStream(resource);
sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
sqlSession=sessionFactory.openSession();
return sqlSession;
}
}
这也是重点中的重点,没有他你肯定回出现问题!!!!
上述代码就完美的体现了上一篇博文的SqlSessionFactory和SqlSession的作用,在这里完美体现,大家一定要仔细看哦!!
下面该配置UserMapper.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="test">
<select id="findUserById" parameterType="int" resultType="javabean.UserBean">
select * from user where id=#{id}
</select>
<select id="findUserByName" parameterType="java.lang.String" resultType="javabean.UserBean">
select * from user where username like '%${value}%'
</select>
<insert id="addUser" parameterType="javabean.UserBean">
insert into user(username,password,gender,birthday,email,province,city) value(#{username},#{password},#{gender},#{birthday,jdbcType=DATE},#{email},#{province},#{city})
</insert>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
<update id="updateUser" parameterType="javabean.UserBean">
update user set username=#{username} where id=#{id}
</update>
</mapper>
增删改查全部都在,标签提示应有尽有,alt+/ 会帮助你的,如果你还是一个对标签一脸懵逼的小白,那你就自己敲一敲,或者看看我的mybatis的第一篇会帮助你的。
配置完UserMapper.xml要注意在SqlMapConfig.xml中配置哦
如果你们先看了第一篇你们一定不会有问题的!!!
下面就来验证是否正确了
上代码
package test;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Ignore;
import org.junit.Test;
import datasource.DataConnection;
import javabean.UserBean;
public class MybatisTest {
public DataConnection connection=new DataConnection();
@Ignore
public void TestSelectById() throws IOException {
SqlSession sqlSession=connection.getSqlSession();
UserBean userBean=sqlSession.selectOne("test.findUserById",2);
System.out.println("姓名"+userBean.getUsername());
System.out.println("性别"+userBean.getGender());
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
System.out.println("生日"+dateFormat.format(userBean.getBirthday()));
System.out.println("所在地"+userBean.getProvince()+userBean.getCity());
sqlSession.close();
}
@Ignore
public void TestSelectByName() throws IOException {
SqlSession sqlSession=connection.getSqlSession();
List<UserBean> list=sqlSession.selectList("test.findUserByName","王");
for (int i = 0; i < list.size(); i++) {
UserBean userBean=list.get(i);
System.out.println("姓名: "+userBean.getUsername());
System.out.println("性别: "+userBean.getGender());
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
System.out.println("生日: "+dateFormat.format(userBean.getBirthday()));
System.out.println("所在地: "+userBean.getProvince()+userBean.getCity());
sqlSession.close();
}
}
@Ignore
public void Testadd() throws IOException, ParseException {
SqlSession sqlSession=connection.getSqlSession();
UserBean userBean=new UserBean();
userBean.setUsername("王小白");
userBean.setPassword("122");
userBean.setGender("男");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
userBean.setBirthday(dateFormat.parse("1999-12-22"));
userBean.setEmail("1289418375@qq.com");
userBean.setProvince("辽宁省");
userBean.setCity("大连市");
sqlSession.insert("test.addUser",userBean);
sqlSession.commit();
sqlSession.close();
}
@Ignore
public void Testdelete() throws IOException {
SqlSession sqlSession=connection.getSqlSession();
sqlSession.delete("test.deleteUser",1);
sqlSession.commit();
sqlSession.close();
}
@Test
public void Testupdate() throws IOException {
SqlSession sqlSession=connection.getSqlSession();
UserBean userBean=new UserBean();
userBean.setId(2);
userBean.setUsername("王小蓝");
sqlSession.update("test.updateUser",userBean);
sqlSession.commit();
sqlSession.close();
}
}
代码中有少量的junit内容,但是一点也不复杂哦,你们一定能看懂的!!
经本小白一点点的调试,上述代码在配置完全正确的情况下不会出现问题的,都是运行成功的!!大家加油啊!
今天是2020年的最后一天了,王小白在此祝所有圈友兄弟,新年快乐!工作顺利,身体健康!!大家在2021年继续加油!