一、无 mybatis 配置文件方式
1.1 配置相关信息
1.1.1 添加 maven 依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
1.1.2 修改 application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/zlits_user?useSSL=false
spring.datasource.username=root
spring.datasource.password=Rfid123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
1.1.3 建库建表
DROP DATABASE IF EXISTS zlits_user;
CREATE DATABASE zlits_user;
USE zlits_user;
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '名字',
`password` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '密码',
`age` bigint(20) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='人员信息表';
1.1.4 项目代码结构
在写用例的工程中发现,这个 main 类需要在根目录下启动才能管理起整个工程来
1.2 编码
1.2.1 mapper 层
@Mapper
public interface UserMapper {
@Select("select id,name,password,age from user")
List<User> findAll();
@Delete("delete from user where id=#{id}")
int deleteUserById(int id);
@Update({"update user set name=#{name},password=#{password},age=#{age} where id=#{id}"})
int updateUserById(User user);
@Insert({"insert into user(name,password,age) values(#{name},#{password},#{age})"})
int insertUser(User user);
@Select({"select * from user where id=#{id}"})
User selectUserById(int id);
}
1.2.2 service 层
public interface UserService {
public List<User> findAll();
int deleteUserById(int id);
int updateUserById(User user);
int insertUser(User user);
User selectUserById(int id);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper mapper;
@Override
public List<User> findAll() {
return mapper.findAll();
}
@Override
public int deleteUserById(int id) {
return mapper.deleteUserById(id);
}
@Override
public int updateUserById(User user) {
return mapper.updateUserById(user);
}
@Override
public int insertUser(User user) {
return mapper.insertUser(user);
}
@Override
public User selectUserById(int id) {
return mapper.selectUserById(id);
}
}
1.2.3 entity 层
public class User {
private int id;
private String name;
private String password;
private int age;
// setter、getter、toString()
}
1.2.4 controller层
@Controller
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/listUser")
public String listUser(Model model) {
List<User> users = userService.findAll();
model.addAttribute("users", users);
System.out.println(addUser());
System.out.println(modifyUser());
System.out.println(deleUser());
return "listUser";
}
//新增
public int addUser() {
User user = new User();
user.setName("张三丰");
user.setAge(80);
user.setPassword("dsdsds");
return userService.insertUser(user);
}
//修改
public int modifyUser() {
User user = userService.selectUserById(1);
user.setName(user.getName()+"A");
user.setAge(user.getAge()+1);
user.setPassword(user.getPassword()+"A");
return userService.updateUserById(user);
}
//删除
public int deleUser() {
return userService.deleteUserById(2);
}
}
1.2.5 jsp 页面
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
<td>password</td>
<td>age</td>
</tr>
<c:forEach items="${users}" var="s" varStatus="st">
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.password}</td>
<td>${s.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
1.2.6 测试
在浏览器输入 http://localhost:8080/listUser
二、有 mybatis 配置文件方式
2.1 配置相关信息
2.1.1添加 maven 依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.1.2 修改 application.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/zlits_user?useSSL=false
spring.datasource.username=root
spring.datasource.password=Rfid123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
# 是否检查配置文件
mybatis.check-config-location =true
#mybatis的配置文件的位置
mybatis.config-location=classpath:mybatis-config.xml
#mybatis的mapper文件的位置
mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
2.1.3 建库建表
DROP DATABASE IF EXISTS zlits_user;
CREATE DATABASE zlits_user;
USE zlits_user;
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`NAME` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '名字',
`PASSWORD` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '密码',
`AGE` bigint(20) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='人员信息表';
2.1.4 项目代码结构
2.2 编码
2.2.1 mapper 层
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> selectAll();
}
2.2.2 entity 层
public class User implements Serializable {
private Long id;
private String name;
private String password;
private Long age;
private static final long serialVersionUID = 1L;
// setter、getter、toString
}
2.2.3 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="com.generator.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.generator.entity.User">
<id column="ID" jdbcType="BIGINT" property="id" />
<result column="NAME" jdbcType="VARCHAR" property="name" />
<result column="PASSWORD" jdbcType="VARCHAR" property="password" />
<result column="AGE" jdbcType="BIGINT" property="age" />
</resultMap>
<sql id="Base_Column_List">
ID, NAME, PASSWORD, AGE
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where ID = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from user
where ID = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.generator.entity.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user (NAME, PASSWORD, AGE
)
values (#{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=BIGINT}
)
</insert>
<insert id="insertSelective" parameterType="com.generator.entity.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
NAME,
</if>
<if test="password != null">
PASSWORD,
</if>
<if test="age != null">
AGE,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=BIGINT},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.generator.entity.User">
update user
<set>
<if test="name != null">
NAME = #{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
PASSWORD = #{password,jdbcType=VARCHAR},
</if>
<if test="age != null">
AGE = #{age,jdbcType=BIGINT},
</if>
</set>
where ID = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.generator.entity.User">
update user
set NAME = #{name,jdbcType=VARCHAR},
PASSWORD = #{password,jdbcType=VARCHAR},
AGE = #{age,jdbcType=BIGINT}
where ID = #{id,jdbcType=BIGINT}
</update>
</mapper>
2.2.4 service 层
public interface UserService {
public List<User> findAll();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper mapper;
public List<User> findAll() {
System.out.println("执行了DAO层");
return mapper.selectAll();
}
}
2.2.5 Controller 层
@Controller
public class UserController {
@Autowired
UserService userService;
// 查询
@RequestMapping("/listUserCommon")
public String listUser(Model model) {
List<User> users = userService.findAll();
for (User user : users) {
System.out.println(user.toString());
}
model.addAttribute("users", users);
return "listUser";
}
}
2.2.6 jsp 页面
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
<td>password</td>
<td>age</td>
</tr>
<c:forEach items="${users}" var="s" varStatus="st">
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.password}</td>
<td>${s.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
2.2.7 测试
在浏览器输入 http://localhost:8080/listUserCommon
2.2.8 说明
如果 UserMapper 类上不添加 @Mapper 注解,那么就得在启动类上添加 @MapperScan 注解,一般情况下都是在启动类上添加 @MapperScan 注解,这样比较简单。
加这个注解的标签主要是为了让 Spring 进行管理,如果有多个 dao,用逗号隔开即可,如下
@MapperScan({"com.zit.cac.dao","com.zit.epms.dao"})