1.自增主键设置(字段是自增的才可使用)
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<!--
将插入数据的主键返回,返回到user对象中
SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键
keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
resultType:指定SELECT LAST_INSERT_ID()的结果类型
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
</insert>
这种设置需要在每个表对应的mapper.xml中逐一设置,对于逆向工程自动生成可以统一设置
2.逆向工程中统一设置
<table tableName="%" >
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
这样设置可以匹配数据库的所有表,同时统一添加自增主键
对于逆向工程配置文件<table>
属性的补充:
a)schema即为数据库名, tableName表名
b)domainObjectName是要生成的实体类,可以通过此属性设置对应的实体类名
c)mapperName可以设置对应的mapper文件名
d)enableCountByExample=”false”
enableUpdateByExample=”false”
enableDeleteByExample=”false”
enableSelectByExample=”false”
selectByExampleQueryId=”false”
设置这些属性为false则不生成相应的Example类
例如:
<table tableName="inst_blog_main" domainObjectName="BlogMain"
mapperName="BlogMainDao"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"/>
e)<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
对于属性identity:文档解释是(If true, then the column is flagged as an identity column and the generated element will be placed after the insert (for an identity column). If false, then the generated will be placed before the insert (typically for a sequence).)
当设置成true生成的inset中是:<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
当设置成true生成的inset中是:<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
也就是对于insert它的执行顺序是在前还是在后
注意:这个<generatedKey>
是<table>
的子标签