本项目功能描述:
用户和博客存在一对多的关系。当删除叫小明的用户时,小明写的所有博客也要删除。当更改小明的id时,小明写的所有博客的userId都要进行更新。
项目结构如下:
User.java
package com.test.pojo;
import java.util.List;
public class User {
private Integer userId;
private String userName;
private String passWord;
private List<Blog> blogs;
public User(){}
public User(Integer userId, String userName, String passWord, List<Blog> blogs) {
this.userId = userId;
this.userName = userName;
this.passWord = passWord;
this.blogs = blogs;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
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 List<Blog> getBlogs() {
return blogs;
}
public void setBlogs(List<Blog> blogs) {
this.blogs = blogs;
}
}
Blog.java
package com.test.pojo;
public class Blog {
private Integer blogId;
private String blogTitle;
private String blogContent;
private Integer userId;
public Blog() {
}
public Blog(Integer blogId, String blogTitle, String blogContent, Integer userId) {
this.blogId = blogId;
this.blogTitle = blogTitle;
this.blogContent = blogContent;
this.userId = userId;
}
public Integer getBlogId() {
return blogId;
}
public void setBlogId(Integer blogId) {
this.blogId = blogId;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}
UserMapper.java
package com.test.mapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface UserMapper {
//根据用户名进行查询用户id
@Select("SELECT userId FROM t_user WHERE userName = #{userName}")
int getUserIdByName(String userName);
//修改
//根据用户名修改用户id
@Update({"UPDATE t_user SET userId=#{arg1} WHERE userName=#{arg0}"})
void updateUser(String userName, int userId);
//根据用户原id修改为用户新id
@Update({"UPDATE t_blog SET userId=#{arg1} WHERE userId=#{arg0}"})
void updateBlogUser( int userId1, int userId);
// 修改,设置参数方法二
// @Update({"UPDATE t_user SET userId=#{userId} WHERE userName=#{userName}"})
// void updateUser(@Param("userName")String userName, @Param("userId")int userId);
// @Update({"UPDATE t_blog SET userId=#{userId} WHERE userId=#{userId1}"})
// void updateBlogUser(@Param("userId1")int userId1, @Param("userId")int userId);
//删除
//根据用户id删除用户数据
@Delete("DELETE FROM t_user WHERE userId=#{userId}")
void deleteUser(int userId);
//根据用户id删除关联博客数据
@Delete("DELETE FROM t_blog WHERE userId=#{userId}")
void deleteBlog(int userId);
}
UserMain.java
package com.test.test;
public class UserMain {
public static void main(String[] args) {
//修改用户名为cvf的id,改为12,且博客userId同步更新
UserTest.updateUserId("cvf",12);
//删除id为8的用户和其写的博客
UserTest.deleteUser(8);
}
}
UserTest.java
package com.test.test;
import com.test.mapper.UserMapper;
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.IOException;
import java.io.Reader;
public class UserTest {
private static SqlSessionFactory sqlSessionFactory;
//初始化
public static void init() {
try {
//读取MyBatis核心配置文件
Reader reader = Resources.getResourceAsReader("mybatis_config.xml");
//通过reader实例化sqlSessionFactory对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
//修改数据
public static void updateUserId(String userName,int userId) {
init();
SqlSession sqlSession = null;
try {
sqlSession =sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int userId1 = mapper.getUserIdByName(userName);
mapper.updateUser(userName,userId);
mapper.updateBlogUser(userId1,userId);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
//删除数据
public static void deleteUser(int userId) {
init();
SqlSession sqlSession = null;
try {
sqlSession =sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(userId);
mapper.deleteBlog(userId);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
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>
<!-- 配置了一个包的别名,之后在使用类的时候不需要写包名的部分,只使用User即可。 -->
<typeAliases>
<package name="com.test.pojo"/>
</typeAliases>
<!--配置数据库连接环境-->
<environments default="development">
<environment id="development">
<!-- 使用JDBC事务管理 -->
<transactionManager type="JDBC"/>
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件(xml文件) -->
<mappers>
<mapper class="com.test.mapper.UserMapper"/>
</mappers>
</configuration>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>mybatis03</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mybatis03 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<!-- 依赖包集合 -->
<dependencies>
<!--MyBatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--数据库相关依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
<scope>runtime</scope>
</dependency>
<!--日志相关依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<!--junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
运行前:mydb.sql
-- ----------------------------
-- Table structure for `t_blog`
-- ----------------------------
DROP TABLE IF EXISTS `t_blog`;
CREATE TABLE `t_blog` (
`blogId` int(11) NOT NULL AUTO_INCREMENT COMMENT '博客ID',
`blogTitle` varchar(100) NOT NULL COMMENT '博客标题',
`blogContent` longtext NOT NULL COMMENT '博客内容',
`userId` int(11) DEFAULT NULL COMMENT '创建人ID',
PRIMARY KEY (`blogId`),
KEY `FK_user_id` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_blog
-- ----------------------------
INSERT INTO `t_blog` VALUES ('1', 'spark练习', 'Apache Spark 是专为大规模数据处理而设计的快速通用的计算引擎。', '5');
INSERT INTO `t_blog` VALUES ('2', 'css学习', '层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。', '2');
INSERT INTO `t_blog` VALUES ('3', 'Mybatis', 'Mybatis学习', '8');
INSERT INTO `t_blog` VALUES ('4', 'hbase', 'HBase是一个分布式的、面向列的开源数据库。', '5');
INSERT INTO `t_blog` VALUES ('5', 'Java', 'Java鸭梨大', '8');
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`userId` int(8) NOT NULL AUTO_INCREMENT,
`userName` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`passWord` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('2', 'dgdf', '465463');
INSERT INTO `t_user` VALUES ('4', 'xgdfg', '53545');
INSERT INTO `t_user` VALUES ('5', 'cvf', '486196');
INSERT INTO `t_user` VALUES ('8', 'dsfddv', '54354');
运行后:mydb.sql
-- ----------------------------
-- Table structure for `t_blog`
-- ----------------------------
DROP TABLE IF EXISTS `t_blog`;
CREATE TABLE `t_blog` (
`blogId` int(11) NOT NULL AUTO_INCREMENT COMMENT '博客ID',
`blogTitle` varchar(100) NOT NULL COMMENT '博客标题',
`blogContent` longtext NOT NULL COMMENT '博客内容',
`userId` int(11) DEFAULT NULL COMMENT '创建人ID',
PRIMARY KEY (`blogId`),
KEY `FK_user_id` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_blog
-- ----------------------------
INSERT INTO `t_blog` VALUES ('1', 'spark练习', 'Apache Spark 是专为大规模数据处理而设计的快速通用的计算引擎。', '12');
INSERT INTO `t_blog` VALUES ('2', 'css学习', '层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。', '2');
INSERT INTO `t_blog` VALUES ('4', 'hbase', 'HBase是一个分布式的、面向列的开源数据库。', '12');
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`userId` int(8) NOT NULL AUTO_INCREMENT,
`userName` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`passWord` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('2', 'dgdf', '465463');
INSERT INTO `t_user` VALUES ('4', 'xgdfg', '53545');
INSERT INTO `t_user` VALUES ('12', 'cvf', '486196');