<!--在主键是自增的情况下使用keyProperty="id" useGeneratedKeys="true",添加成功后可以直接使用主键值,其中keyProperty的值是对象的属性值,而不是数据库表中的字段名--> <insert id="insertSelective" parameterType="com.xxx.entity.UserEntity" keyProperty="id" useGeneratedKeys="true"> .... </insert>
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>com.zsk</groupId> <artifactId>mybatis-normal-demo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </project>
jdbc.properties
db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://127.0.0.1:3306/test_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai db.username=root db.password=root
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> <!--引入jdbc.propeties文件--> <properties resource="jdbc.properties"/> <settings> <!-- 驼峰映射 --> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <environments default="development"> <!-- environment:某一个环境 id:就是这个环境的名称--> <environment id="development"> <!-- transactionManager:事务管理(ACID) type="JDBC|MANAGED" jdbc:简单jdbc事务 MANAGED:啥都不做 --> <transactionManager type="JDBC"/> <!-- 数据源(连接池) POOLED:mybatis内置的连接池 --> <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> <!--配置映射xml--> <mapper resource="com/zsk/IAttrInfoIDao.xml"/> </mappers> </configuration>
dao/mapper.java
package com.zsk.dao; import com.zsk.entity.AttrInfo; import org.apache.ibatis.annotations.Param; import java.util.List; public interface IAttrInfoIDao { int deleteByPrimaryKey(Long id); int insert(AttrInfo record); int insertSelective(AttrInfo record); AttrInfo selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(AttrInfo record); int updateByPrimaryKey(AttrInfo record); int batchInsert(List<AttrInfo> list); List<AttrInfo> findByName(@Param("name") String name); int deleteByName(@Param("name") String name); boolean existByName(@Param("name") String name); }
dao/mapper.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.zsk.dao.IAttrInfoIDao"> <resultMap id="BaseResultMap" type="com.zsk.entity.AttrInfo"> <id column="id" jdbcType="BIGINT" property="id"/> <result column="name" jdbcType="VARCHAR" property="name"/> <result column="value" jdbcType="BIGINT" property="value"/> <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/> <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/> </resultMap> <sql id="Base_Column_List"> id, `name`, `value`, create_time, update_time </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from attr_info where id = #{id,jdbcType=BIGINT} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from attr_info where id = #{id,jdbcType=BIGINT} </delete> <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.zsk.entity.AttrInfo" useGeneratedKeys="true"> insert into attr_info (`name`, `value`, create_time, update_time) values (#{name,jdbcType=VARCHAR}, #{value,jdbcType=BIGINT}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}) </insert> <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.zsk.entity.AttrInfo" useGeneratedKeys="true"> insert into attr_info <trim prefix="(" suffix=")" suffixOverrides=","> <if test="name != null"> `name`, </if> <if test="value != null"> `value`, </if> <if test="createTime != null"> create_time, </if> <if test="updateTime != null"> update_time, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="name != null"> #{name,jdbcType=VARCHAR}, </if> <if test="value != null"> #{value,jdbcType=BIGINT}, </if> <if test="createTime != null"> #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> #{updateTime,jdbcType=TIMESTAMP}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zsk.entity.AttrInfo"> update attr_info <set> <if test="name != null"> `name` = #{name,jdbcType=VARCHAR}, </if> <if test="value != null"> `value` = #{value,jdbcType=BIGINT}, </if> <if test="createTime != null"> create_time = #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> update_time = #{updateTime,jdbcType=TIMESTAMP}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <update id="updateByPrimaryKey" parameterType="com.zsk.entity.AttrInfo"> update attr_info set `name` = #{name,jdbcType=VARCHAR}, `value` = #{value,jdbcType=BIGINT}, create_time = #{createTime,jdbcType=TIMESTAMP}, update_time = #{updateTime,jdbcType=TIMESTAMP} where id = #{id,jdbcType=BIGINT} </update> <insert id="batchInsert" parameterType="java.util.List"> insert into attr_info (`name`, `value`,`id`, create_time, update_time) values <foreach collection="list" item="item" separator=","> ( #{item.name}, #{item.value}, <include refid="common_col_class"/> ) </foreach> </insert> <sql id="common_col"> id, create_time, update_time </sql> <sql id="common_col_class"> #{item.id}, #{item.createTime},#{item.updateTime} </sql> <select id="findByName" resultType="com.zsk.entity.AttrInfo"> select name,value, <include refid="common_col"/> from attr_info where `name` = #{name} </select> <delete id="deleteByName"> delete from attr_info where `name` = #{name} </delete> <select id="existByName" resultType="boolean"> SELECT (SELECT COUNT(id) FROM attr_info WHERE name = #{name})>0 as res </select> </mapper>
使用
// 加载 mybatis 全局配置文件 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mybatis-config.xml"); // 构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 根据 sqlSessionFactory 产生 session SqlSession session = sessionFactory.openSession(); IAttrInfoIDao attrDao = session.getMapper(IAttrInfoIDao.class); // 如果是insert/update需要提交 session.commit(); session.close();