ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

mybatis 映射mysql

2021-09-22 10:04:16  阅读:106  来源: 互联网

标签:username 映射 spring public mysql mybatis import password id


mybatis 映射mysql

step1: F:\project\goodsql52\goodQuery\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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.2</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.MyRedis</groupId>
  <artifactId>test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>test</name>
  <description>Demo project for Spring Boot</description>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>

    </dependency>
    <!--  thymeleaf模板引擎-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j</artifactId>
      <version>1.3.8.RELEASE</version>
    </dependency>


    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- Spring Boot Redis依赖 -->
    <!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <!-- 1.5的版本默认采用的连接池技术是jedis  2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
      <exclusions>
        <exclusion>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
        </exclusion>
        <exclusion>
          <groupId>io.lettuce</groupId>
          <artifactId>lettuce-core</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- 添加jedis客户端 -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
    </dependency>

    <!--spring2.0集成redis所需common-pool2-->
    <!-- 必须加上,jedis依赖此  -->
    <!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>2.5.0</version>
    </dependency>

    <!-- 将作为Redis对象序列化器 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>
    <!---->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.2.0</version>
    </dependency>
    <!---->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration> <fork>true</fork> </configuration>
      </plugin>
    </plugins>
  </build>

</project>

step2: F:\project\goodsql52\goodQuery\src\main\resources\application.properties

server.port=8088
server.servlet.context-path=/
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html

spring.datasource.url=jdbc:mysql://localhost/gft?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=gft123456

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations= classpath:**/mapper/*.xml
spring.datasource.druid.initial-size= 5
spring.datasource.druid.min-idle= 5
spring.datasource.druid.max-active= 20
spring.datasource.druid.max-wait= 60000
spring.datasource.druid.time-between-eviction-runs-millis= 60000
spring.datasource.druid.min-evictable-idle-time-millis= 300000 
spring.datasource.druid.validation-query= SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle= true
spring.datasource.druid.test-on-borrow= false
spring.datasource.druid.test-on-return= false
spring.datasource.druid.pool-prepared-statements= true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size= 20
spring.datasource.druid.filters= stat,wall
spring.datasource.druid.use-global-data-source-stat= true
spring.datasource.druid.connect-properties= druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.datasource.druid.stat-view-servlet.login-username= admin
spring.datasource.druid.stat-view-servlet.login-password=123456
spring.datasource.druid.reset-enable= false
spring.datasource.druid.stat-view-servlet.url-pattern= /druid/*
spring.datasource.druid.web-stat-filter=
spring.datasource.druid.url-pattern= /* #��ӹ��˹���
spring.datasource.druid.exclusions= "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #���Թ��˸�ʽ


spring.redis.database=0
spring.redis.host=192.168.52.129
spring.redis.port=6379
spring.redis.password=123456
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=3000

step3: F:\project\goodsql52\goodQuery\src\main\resources\mapper\UserDao.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.myredis.test.dao.UserDao">
    <resultMap id="BaseResultMap" type="com.myredis.test.entity.UserEntity">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="username" jdbcType="VARCHAR" property="username" />
        <result column="password" jdbcType="VARCHAR" property="password" />
        <result column="createtime" jdbcType="TIMESTAMP" property="createtime" />
    </resultMap>
    <sql id="Base_Column_List">
        id, username, `password`, createtime
    </sql>

    <select id="selectAllPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from user
    </select>

    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from user
        where id = #{id,jdbcType=INTEGER}
    </select>

    <select id="getListByPatameter" parameterType="map" resultMap="BaseResultMap">
        select <include refid="Base_Column_List"/> from user
        <where>
            <if test="username !=null and username !=''">
                and username = #{username}
            </if>
            <if test="password !=null and password !=''">
                and password = #{password}
            </if>
            <if test="createtime !=null and createtime !=''">
                and createtime like concat('%',#{createtime},'%')
            </if>


        </where>
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from user
        where id = #{id,jdbcType=INTEGER}
    </delete>
    <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.myredis.test.entity.UserEntity" useGeneratedKeys="true">
        insert into user (id,username, `password`, createtime
        )
        values (#{id,jdbcType=INTEGER},#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}
               )
    </insert>
    <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.myredis.test.entity.UserEntity" useGeneratedKeys="true">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username != null">
                username,
            </if>
            <if test="password != null">
                `password`,
            </if>
            <if test="createtime != null">
                createtime,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="username != null">
                #{username,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="createtime != null">
                #{createtime,jdbcType=TIMESTAMP},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.myredis.test.entity.UserEntity">
        update user
        <set>
            <if test="username != null">
                username = #{username,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                `password` = #{password,jdbcType=VARCHAR},
            </if>
            <if test="createtime != null">
                createtime = #{createtime,jdbcType=TIMESTAMP},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.myredis.test.entity.UserEntity">
        update user
        set username = #{username,jdbcType=VARCHAR},
            `password` = #{password,jdbcType=VARCHAR},
            createtime = #{createtime,jdbcType=TIMESTAMP}
        where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>

step4: F:\project\goodsql52\goodQuery\src\main\java\com\myredis\test\TestApplication.java

package com.myredis.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

step5: F:\project\goodsql52\goodQuery\src\main\java\com\myredis\test\service\UserService.java

package com.myredis.test.service;

import com.myredis.test.entity.UserEntity;

import java.util.List;
import java.util.Map;

public interface UserService {
    UserEntity selectByPrimaryKey(Integer id);  //query single

    List<UserEntity> selectAllPrimaryKey();  //query  all

    UserEntity getListByPatameter(String username, String password, String createtime);  //多条件查询

    int deleteByPrimaryKey(Integer id);  //delete

    int insert(UserEntity record);
}

step6: F:\project\goodsql52\goodQuery\src\main\java\com\myredis\test\service\impl\UserServiceImpl.java

package com.myredis.test.service.impl;

import com.myredis.test.dao.UserDao;
import com.myredis.test.entity.UserEntity;
import com.myredis.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserEntity selectByPrimaryKey(Integer id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public List<UserEntity> selectAllPrimaryKey() {
        return userDao.selectAllPrimaryKey();
    }

    @Override
    public UserEntity getListByPatameter(String username, String password, String createtime) {
        return userDao.getListByPatameter(username,password,createtime);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userDao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(UserEntity record) {
        return userDao.insert(record);
    }
}

step7: F:\project\goodsql52\goodQuery\src\main\java\com\myredis\test\entity\UserEntity.java

package com.myredis.test.entity;

import java.io.Serializable;
import java.util.Date;

/**
 * user
 * @author
 */
public class UserEntity implements Serializable {
    /**
     * 主键
     */
    private Integer id;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 创建时间
     */
    private Date createtime;

    private static final long serialVersionUID = 1L;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        UserEntity other = (UserEntity) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
                && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
                && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()))
                && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
        result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode());
        result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode());
        return result;
    }

    @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(", username=").append(username);
        sb.append(", password=").append(password);
        sb.append(", createtime=").append(createtime);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

step8: F:\project\goodsql52\goodQuery\src\main\java\com\myredis\test\dao\UserDao.java

package com.myredis.test.dao;

import com.myredis.test.entity.UserEntity;
import com.myredis.test.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;

import java.util.List;
import java.util.Map;

/**
 * UserDao继承基类
 */
@Mapper
public interface UserDao{

    int deleteByPrimaryKey(Integer id);

    int insert(UserEntity record);

    int insertSelective(UserEntity record);

    UserEntity selectByPrimaryKey(Integer id);

    List<UserEntity> selectAllPrimaryKey();

    UserEntity getListByPatameter(String username,String password,String createtime);

    int updateByPrimaryKeySelective(UserEntity record);

    int updateByPrimaryKey(UserEntity record);

    List<UserEntity> getListByPatameter(Map<String, Object> map);
}

step9: F:\project\goodsql52\goodQuery\src\main\java\com\myredis\test\controller\IndexController.java

package com.myredis.test.controller;

import com.myredis.test.entity.UserEntity;
import com.myredis.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("api")
public class IndexController {
    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/query")
    public UserEntity query() {
        UserEntity mUserEntity = userService.selectByPrimaryKey(1);
        return mUserEntity;
    }

    @ResponseBody
    @RequestMapping("/get")
    public UserEntity get() {
        UserEntity mUserEntity = userService.getListByPatameter("gft", "123456", "2017-12-18");
        return mUserEntity;
    }

    @ResponseBody
    @RequestMapping("/all")
    public List<UserEntity> all() {
        List<UserEntity> list = userService.selectAllPrimaryKey();
        return list;
    }

    @ResponseBody
    @RequestMapping("/delete")
    public int delete() {
        int deleteId = userService.deleteByPrimaryKey(4);
        return deleteId;
    }

    @ResponseBody
    @RequestMapping("/insert")
    public int insert() {
        UserEntity mUserEntity = new UserEntity();
        mUserEntity.setId(109);
        mUserEntity.setUsername("张飞");
        mUserEntity.setPassword("123456");
        mUserEntity.setCreatetime(stringToDate("2021-09-18"));
        int insertId = userService.insert(mUserEntity);
        return insertId;
    }

    @RequestMapping(value = {"/postman"}, method = RequestMethod.POST)
    public String getQuery(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String id = request.getParameter("id");
        System.out.println(id + "\t");
        return "user";
    }

    public static Date stringToDate(String time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");//日期格式
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

}

run http://localhost:8088/api/all

[
    {
        "id": 1,
        "username": "ygz",
        "password": "123456",
        "createtime": "2021-06-04T16:00:00.000+00:00"
    },
    {
        "id": 2,
        "username": "gft",
        "password": "123456",
        "createtime": "2017-12-17T16:00:00.000+00:00"
    },
    {
        "id": 3,
        "username": "liwei",
        "password": "123456",
        "createtime": "2017-12-17T16:00:00.000+00:00"
    },
    {
        "id": 5,
        "username": "张飞",
        "password": "123456",
        "createtime": "2021-09-17T16:00:00.000+00:00"
    },
    {
        "id": 108,
        "username": "张飞",
        "password": "123456",
        "createtime": "2021-09-17T16:00:00.000+00:00"
    },
    {
        "id": 109,
        "username": "张飞",
        "password": "123456",
        "createtime": "2021-09-17T16:00:00.000+00:00"
    }
]

标签:username,映射,spring,public,mysql,mybatis,import,password,id
来源: https://blog.csdn.net/cf8833/article/details/120409739

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有