1. 程式人生 > 實用技巧 >Mybatis 插入後獲取主鍵

Mybatis 插入後獲取主鍵

專案結構

資料表結構

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>net.cyb</groupId> <artifactId>cyb-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</
artifactId> <version>3.5.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency
> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.30</version> </dependency> </dependencies> </project>

mybatis-config.xml

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 引入外部配置檔案 -->
    <properties resource="config/db.properties"></properties>
    <!--下劃線自動對映駝峰欄位-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 資料庫連結相關 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 新增對映檔案 -->
        <mapper resource="mapper/VideoMapper.xml" />
    </mappers>
</configuration>

db.properties

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/cybclass
db.username=root
db.password=root

log4j.properties

#dev env [debug] product env [info]
log4j.rootLogger=ERROR, stdout
# Console output...
# 細化到列印某個mapper
# log4j.logger.包名.方法名=TRACE
log4j.logger.net.cybclass.online=TRACE
#log4j.logger.net.cybclass.online.dao.VideoMapper.selectById=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

VideoMapper.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">
<!--
namespace:名稱空間,一般需要保持全域性唯一,最好是和dao層的java介面一致。可以對映sql語句到對應的方法名稱和引數、返回型別
-->
<mapper namespace="net.cybclass.online.dao.VideoMapper">
    <insert id="add" parameterType="net.cybclass.online.domain.Video">
        insert into video (title,summary,cover_img,price,c_id,point,create_time) values
        (#{title,jdbcType=VARCHAR},#{summary,jdbcType=VARCHAR},#{coverImg,jdbcType=VARCHAR},#{price,jdbcType=INTEGER},#{c_id,jdbcType=INTEGER},#{point,jdbcType=DOUBLE},#{create_time,jdbcType=TIMESTAMP})
    </insert>
</mapper>

VideoMapper.java

package net.cybclass.online.dao;

import net.cybclass.online.domain.Video;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface VideoMapper {
    /**
     * 根據視訊id查詢視訊物件
     * @param videoId
     * @return
     */
    Video selectById(@Param("video_id") int videoId);

    /**
     * 查詢全部視訊列表
     * @return
     */
    @Select("select * from video")
    List<Video> selectList();

    /**
     * 查詢全部視訊列表
     * @return
     */
    List<Video> selectListByXml();

    /**
     * 根據評分和標題模糊查詢
     * @param point
     * @param title
     * @return
     */
    List<Video> selectByPointAndTitleLike(@Param("point") double point,@Param("title") String title);

    /**
     * 新增一個視訊記錄
     * @param video
     * @return
     */
    int add(Video video);
}

Video.java

package net.cybclass.online.domain;

import java.util.Date;

/**
 * 視訊類
 */
public class Video {
    //內碼
    private int id;
    //視訊標題
    private String title;
    //視訊詳情
    private String summary;
    //視訊封面
    private String coverImg;
    //加個
    private int price;
    private int c_id;
    //評分
    private double point;
    //建立日期
    private Date create_time;

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getCoverImg() {
        return coverImg;
    }

    public void setCoverImg(String coverImg) {
        this.coverImg = coverImg;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getC_id() {
        return c_id;
    }

    public void setC_id(int c_id) {
        this.c_id = c_id;
    }

    public double getPoint() {
        return point;
    }

    public void setPoint(double point) {
        this.point = point;
    }

    public Date getCreate_time() {
        return create_time;
    }

    public void setCreate_time(Date create_time) {
        this.create_time = create_time;
    }

    @Override
    public String toString() {
        return "Video{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", summary='" + summary + '\'' +
                ", coverImg='" + coverImg + '\'' +
                ", price=" + price +
                ", c_id=" + c_id +
                ", point=" + point +
                ", create_time=" + create_time +
                '}';
    }
}

SqlSessionDemo.java

package net.cybclass.online;

import net.cybclass.online.dao.VideoMapper;
import net.cybclass.online.domain.Video;
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.InputStream;
import java.util.Date;

public class SqlSessionDemo {
    public static void main(String[] args) throws IOException {
        String resouce="config/mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resouce);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        try(SqlSession session=build.openSession()){
            VideoMapper mapper = session.getMapper(VideoMapper.class);
            Video video=new Video();
            video.setTitle("測試A");
            video.setSummary("這是一條測試資料");
            video.setCoverImg("www.baidu.com");
            video.setC_id(6);
            video.setPoint(8.88);
            video.setPrice(98);
            video.setCreate_time(new Date());
            mapper.add(video);
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

主鍵返回

    <insert id="add" parameterType="net.cybclass.online.domain.Video" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
        insert into video (title,summary,cover_img,price,c_id,point,create_time) values
        (#{title,jdbcType=VARCHAR},#{summary,jdbcType=VARCHAR},#{coverImg,jdbcType=VARCHAR},#{price,jdbcType=INTEGER},#{c_id,jdbcType=INTEGER},#{point,jdbcType=DOUBLE},#{create_time,jdbcType=TIMESTAMP})
    </insert>
package net.cybclass.online;

import net.cybclass.online.dao.VideoMapper;
import net.cybclass.online.domain.Video;
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.InputStream;
import java.util.Date;

public class SqlSessionDemo {
    public static void main(String[] args) throws IOException {
        String resouce="config/mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resouce);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        try(SqlSession session=build.openSession()){
            VideoMapper mapper = session.getMapper(VideoMapper.class);
            Video video=new Video();
            video.setTitle("測試A");
            video.setSummary("這是一條測試資料");
            video.setCoverImg("www.baidu.com");
            video.setC_id(6);
            video.setPoint(8.88);
            video.setPrice(98);
            video.setCreate_time(new Date());
            int rows=mapper.add(video);
            session.commit();
            System.out.println(rows);
            System.out.println(video.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

插入的時候,自動就把id賦值給Video實體類物件中