mybatis学习(27):获取自增id方式一(在mapper中insert配置节点的属性)

简介: mybatis学习(27):获取自增id方式一(在mapper中insert配置节点的属性)

image.png

com.geyao.mybatis.mapper
BlogMapper类
package com.geyao.mybatis.mapper;
 import java.util.List;
 import java.util.Map;
 import org.apache.ibatis.annotations.Param;
 import com.geyao.mybatis.pojo.Blog;
 public interface BlogMapper {
     Blog selectBlog(Integer id);
     Blog selectBlog2(Integer id);
     List<Blog> selectBlogByTitle(String title);
     List<Blog> selectBlogByTitle2(String title);
     List<Blog> selectBlogBySort(String column);
     List<Blog> selectBlogByPage(int offset,int pagesize);
     List<Blog> selectBlogByPage1(@Param(value="offset")int offset,@Param(value="pagesize")int pagesize);
     List<Blog> selectBlogByPage2(Map<String, Object>map);
     int insertBlog(Blog blog);
 }
 BlogMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
  -->
 <mapper namespace="com.geyao.mybatis.mapper.BlogMapper">
     <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
     使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
     resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回
     User类就是users表所对应的实体类
     -->
     <!-- 
         根据id查询得到一个user对象
      -->
      <resultMap type="Blog" id="blogResultMap">
      <id column="id" property="id" jdbcType="INTEGER"></id>
          <result column="authod_id" property="authodId" jdbcType="INTEGER"/>
      </resultMap>
     <select id="selectBlog" parameterType="int"   resultType="Blog">
         select 
         id,
         title,
         authod_id as authodId,
         state,
         featured,
         style
          from Blog where id=#{id}
     </select> 
     <select id="selectBlog2" parameterType="int"  resultMap="blogResultMap">
           select *
          from Blog where id=#{id}
     </select>
     <select id="selectBlogByTitle" parameterType="String" resultMap="blogResultMap">
         select * from Blog where title like #{title}
     </select>
     <select id="selectBlogByTitle2" parameterType="String" resultMap="blogResultMap">
         select * from Blog where title like '${value}'
     </select>
      <select id="selectBlogBySort" parameterType="String" resultMap="blogResultMap">
         select * from Blog order by ${value}
     </select>
       <select id="selectBlogByPage"  resultMap="blogResultMap">
         select * from Blog limit #{0},#{1}
     </select>
      <select id="selectBlogByPage1"  resultMap="blogResultMap">
         select * from Blog limit #{offset},#{pagesize}
     </select>
      <select id="selectBlogByPage2"  resultMap="blogResultMap">
         select * from Blog limit #{offset},#{pagesize}
     </select>
      <insert id="insertBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="id">
         INSERT INTO Blog(
         title,
         authod_id,
         state,
         featured,
         style
         )
         VALUES(
         #{title},
         #{authodId},
         #{state},
         #{featured},
         #{style}
         )
     </insert>
 </mapper>
 com.geyao.mybatis.pojoBlog类
package com.geyao.mybatis.pojo;
 public class Blog {
     private Integer id;
     private String title;
     private int authodId;
     private String state;
     private Boolean featured;
     private String style;
     public Blog() {
         super();
         this.title="未命名";
         this.authodId=4;
         this.state="NOT";
         this.featured=false;
         this.style="red";    
     }
     public Integer getId() {
         return id;
     }
     public void setId(Integer id) {
         this.id = id;
     }
     public String getTitle() {
         return title;
     }
     public void setTitle(String title) {
         this.title = title;
     }
     public int getAuthodId() {
         return authodId;
     }
     public void setAuthodId(int authodId) {
         this.authodId = authodId;
     }
     public String getState() {
         return state;
     }
     public void setState(String state) {
         this.state = state;
     }
     public Boolean getFeatured() {
         return featured;
     }
     public void setFeatured(Boolean featured) {
         this.featured = featured;
     }
     public String getStyle() {
         return style;
     }
     public void setStyle(String style) {
         this.style = style;
     }
     @Override
     public String toString() {
         return "Blog [id=" + id + ", title=" + title + ", authodId=" + authodId + ", state=" + state + ", featured="
                 + featured + ", style=" + style + "]\n";
     }
 }
 com.geyao.mybatis.utilMybatisUtil类
package com.geyao.mybatis.util;
 import java.io.InputStream;
 import java.io.Reader;
 import org.apache.ibatis.io.Resources;
 import org.apache.ibatis.session.SqlSession;
 import org.apache.ibatis.session.SqlSessionFactory;
 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 public class MyBatisUtil {
     private static SqlSessionFactory sqlSessionFactory =null;
     static {
         try {
             InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
     private MyBatisUtil() {}
     public static SqlSession getSqlSession() {
         return sqlSessionFactory.openSession();
     }
 }
 log4j.properties### \u914D\u7F6E\u6839 ###
 log4j.rootLogger = debug,console ,fileAppender,dailyRollingFile,ROLLING_FILE,MAIL,DATABASE
 ### \u8BBE\u7F6E\u8F93\u51FAsql\u7684\u7EA7\u522B\uFF0C\u5176\u4E2Dlogger\u540E\u9762\u7684\u5185\u5BB9\u5168\u90E8\u4E3Ajar\u5305\u4E2D\u6240\u5305\u542B\u7684\u5305\u540D ###
 log4j.logger.org.apache=dubug
 log4j.logger.java.sql.Connection=dubug
 log4j.logger.java.sql.Statement=dubug
 log4j.logger.java.sql.PreparedStatement=dubug
 log4j.logger.java.sql.ResultSet=dubug
 ### \u914D\u7F6E\u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
 log4j.appender.console = org.apache.log4j.ConsoleAppender
 log4j.appender.console.Target = System.out
 log4j.appender.console.layout = org.apache.log4j.PatternLayout
 log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n
 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>
 <typeAliases>
     <typeAlias type="com.geyao.mybatis.pojo.Blog" alias="Blog"/>
 </typeAliases>
     <environments default="development">
         <environment id="development">
             <transactionManager type="JDBC" />
             <!-- 配置数据库连接信息 -->
             <dataSource type="POOLED">
                 <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8" />
                 <property name="username" value="root" />
                 <property name="password" value="123" />
             </dataSource>
         </environment>
     </environments>
       <mappers>
         <!-- 注册userMapper.xml文件, 
          userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
          <mapper resource="com/geyao/mybatis/mapper/BlogMapper.xml"/>
      </mappers>
 </configuration>
 单元测试com.geyao.mybatis.util
testSelectBlog类
package com.geyao.mybatis.mapper;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import org.apache.ibatis.session.SqlSession;
 import org.junit.Test;
 import com.geyao.mybatis.pojo.Blog;
 import com.geyao.mybatis.util.MyBatisUtil;
 public class testSelectBlog {
     @Test
     public void testSelectBlogNoInterface() {
         SqlSession session =MyBatisUtil.getSqlSession();
         Blog blog =(Blog)session.selectOne("com.geyao.mybatis.mapper.BlogMapper.selectBlog", 101);
         session.close();
         System.out.println(blog);
     }
 @Test
 public void testSelectBlog() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     Blog blog = blogMapper.selectBlog(1);
     System.out.println(blog);
 }
 @Test
 public void testSelectBlog2() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     Blog blog = blogMapper.selectBlog2(1);
     System.out.println(blog);
 }
 @Test
 public void testselectBlogByTitle() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     List<Blog> blogList = blogMapper.selectBlogByTitle("%g%");
     System.out.println(blogList);
 }
 @Test
 public void testselectBlogByTitle2() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     List<Blog> blogList = blogMapper.selectBlogByTitle2("%g%");
     System.out.println(blogList);
 }
 @Test
 public void testselectBlogBySort() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     List<Blog> blogList = blogMapper.selectBlogBySort("title");
     System.out.println(blogList);
 }
 @Test
 public void testselectBlogByPage() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     List<Blog> blogList = blogMapper.selectBlogByPage(2,2);
     System.out.println(blogList);
 }
 @Test
 public void testselectBlogByPage1() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     List<Blog> blogList = blogMapper.selectBlogByPage1(2,2);
     System.out.println(blogList);
 }
 @Test
 public void testselectBlogByPage2() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     Map<String, Object> map =new HashMap<String, Object>();
     map.put("offset", 2);
     map.put("pagesize", 2);
     List<Blog> blogList = blogMapper.selectBlogByPage2(map);
     System.out.println(blogList);
 }
 @Test
 public void testInsertBlog() {
     SqlSession session =MyBatisUtil.getSqlSession();
     BlogMapper blogMapper =session.getMapper(BlogMapper.class);
     Blog blog=new Blog();
     int count= blogMapper.insertBlog(blog);
     session.commit();
     session.close();
     System.out.println(blog);
     System.out.println("插入的"+count+"记录");
 }
 }

image.png

相关文章
|
2月前
|
缓存 NoSQL Java
Mybatis学习:Mybatis缓存配置
MyBatis缓存配置包括一级缓存(事务级)、二级缓存(应用级)和三级缓存(如Redis,跨JVM)。一级缓存自动启用,二级缓存需在`mybatis-config.xml`中开启并配置映射文件或注解。集成Redis缓存时,需添加依赖、配置Redis参数并在映射文件中指定缓存类型。适用于查询为主的场景,减少增删改操作,适合单表操作且表间关联较少的业务。
|
6月前
|
SQL XML Java
mybatis复习01,简单配置让mybatis跑起来
文章介绍了MyBatis的基本概念、历史和特点,并详细指导了如何配置MyBatis环境,包括创建Maven项目、添加依赖、编写核心配置文件、创建数据表和实体类、编写Mapper接口和XML配置文件,以及如何编写工具类和测试用例。
mybatis复习01,简单配置让mybatis跑起来
|
5月前
|
Java 关系型数据库 MySQL
springboot学习五:springboot整合Mybatis 连接 mysql数据库
这篇文章是关于如何使用Spring Boot整合MyBatis来连接MySQL数据库,并进行基本的增删改查操作的教程。
970 0
springboot学习五:springboot整合Mybatis 连接 mysql数据库
|
6月前
|
Java 关系型数据库 数据库连接
mybatis-plus学习
MyBatis-Plus ,MyBatis 最佳搭档,只做增强不做改变,为简化开发、提高效率而生。
75 5
|
5月前
|
SQL Java 数据库连接
Mybatis的<insert>,<update>,<delete>标签用法
这篇文章详细讲解了Mybatis中<insert>, <update>, <delete>标签的使用方法,并提供了示例代码来展示如何执行数据库的增删改操作。
392 0
|
2月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
93 2
|
5月前
|
Java 数据库连接 Maven
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和MyBatis Generator,使用逆向工程来自动生成Java代码,包括实体类、Mapper文件和Example文件,以提高开发效率。
238 2
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
|
5月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
154 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
5月前
|
前端开发 Java Apache
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
本文详细讲解了如何整合Apache Shiro与Spring Boot项目,包括数据库准备、项目配置、实体类、Mapper、Service、Controller的创建和配置,以及Shiro的配置和使用。
1059 1
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
|
6月前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理