spring boot集成mybatis(二)

       简介:以前写过一篇关于spring boot集成mybatis的文章,不过那篇文章是基于注解的,没有以xml的形式加载,这片文章比较通俗,完全是基于部分xml风格的,现在简单介绍下,以前那篇文章的地址在https://blog.csdn.net/xhf852963/article/details/98724831

第一步:添加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>

第二步:在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

第三步:建库建表

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='人员信息表';

第四步:工程代码结构如下 

第五步:服务端代码如下 

       UserMapper类

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

       User类

public class User implements Serializable {
    private Long id;

    private String name;

    private String password;

    private Long age;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", name=").append(name);
        sb.append(", password=").append(password);
        sb.append(", age=").append(age);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

       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>

       UserService接口及实现类

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

       UserController类

@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";
	}
}

       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>

       在浏览器输入http://localhost:8080/listUserCommon

       简要说明:如果在UserMapper类上不添加@Mapper类,那么就得在 启动类上添加@MapperScan 注解,一般情况下都是在启动类上添加@MapperScan注解,如果类比较多的话统一加一个标签就够了,加这个注解的标签主要是为了让spring进行管理,如果有多个dao,用逗号隔开即可@MapperScan({"com.zit.cac.dao","com.zit.epms.dao"}) 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐的小三菊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值