/selectKey> insert id="insertUser" >selectKey keyColumn="id" resultType="long" keyProperty="userId" order="BEFORE">SELECT USE。有关mybatis知识点解析 mybatis调用存储过程( 六 )。" />

有关mybatis知识点解析 mybatis调用存储过程( 六 )


<selectKey keyColumn="id" resultType="long" keyProperty="id" order="BEFORE"></selectKey> <insert id="insertUser" ><selectKey keyColumn="id" resultType="long" keyProperty="userId" order="BEFORE">SELECT USER_ID.nextval as id from dual </selectKey> insert into user( user_id,user_name, user_password, create_time) values(#{userId},#{userName}, #{userPassword} , #{createTime, jdbcType= TIMESTAMP})</insert>此时会将Oracle生成的主键值赋予userId变量 。这个userId 就是USER对象的属性,这样就可以将生成的主键值返回了 。如果仅仅是在insert语句中使用但是不返回,此时keyProperty=“任意自定义变量名”,resultType 可以不写 。
Oracle 数据库中的值要设置为 BEFORE ,这是因为 Oracle中需要先从序列获取值,然后将值作为主键插入到数据库中 。
扩展如果Mysql 使用selectKey的方式获取主键,需要注意下面两点:
order : AFTER获取递增主键值 :SELECT LAST_INSERT_ID()
当实体类中的属性名和表中的字段名不一样 ,怎么办第1种: 通过在查询的SQL语句中定义字段名的别名,让字段名的别名和实体类的属性名一致 。
<select id="getOrder" parameterType="int" resultType="com.jourwon.pojo.Order">select order_id id, order_no orderno ,order_price price form orders where order_id=#{id};</select>第2种: 通过<resultMap>来映射字段名和实体类属性名的一一对应的关系 。
<select id="getOrder" parameterType="int" resultMap="orderResultMap">select * from orders where order_id=#{id}</select><resultMap type="com.jourwon.pojo.Order" id="orderResultMap"><!–用id属性来映射主键字段–><id property="id" column="order_id"><!–用result属性来映射非主键字段,property为实体类属性名,column为数据库表中的属性–><result property ="orderno" column ="order_no"/><result property="price" column="order_price" /></reslutMap>Mapper 编写有哪几种方式?第一种:接口实现类继承 SqlSessionDaoSupport:使用此种方法需要编写mapper 接口,mapper 接口实现类、mapper.xml 文件 。
(1)在 sqlMapConfig.xml 中配置 mapper.xml 的位置
<mappers><mapper resource="mapper.xml 文件的地址" /><mapper resource="mapper.xml 文件的地址" /></mappers>(2)定义 mapper 接口
(3)实现类集成 SqlSessionDaoSupport
mapper 方法中可以 this.getSqlSession()进行数据增删改查 。
(4)spring 配置
<bean id=" " class="mapper 接口的实现"><property name="sqlSessionFactory"ref="sqlSessionFactory"></property></bean>第二种:使用 org.mybatis.spring.mapper.MapperFactoryBean:
(1)在 sqlMapConfig.xml 中配置 mapper.xml 的位置,如果 mapper.xml 和mappre 接口的名称相同且在同一个目录,这里可以不用配置 。
<mappers><mapper resource="mapper.xml 文件的地址" /><mapper resource="mapper.xml 文件的地址" /></mappers>(2)定义 mapper 接口:
(3)mapper.xml 中的 namespace 为 mapper 接口的地址
(4)mapper 接口中的方法名和 mapper.xml 中的定义的 statement 的 id 保持一致
(5)Spring 中定义
<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="mapperInterface" value="https://www.520longzhigu.com/diannao/mapper 接口地址" /><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>第三种:使用 mapper 扫描器:
(1)mapper.xml 文件编写:
mapper.xml 中的 namespace 为 mapper 接口的地址;
mapper 接口中的方法名和 mapper.xml 中的定义的 statement 的 id 保持一致;
如果将 mapper.xml 和 mapper 接口的名称保持一致则不用在 sqlMapConfig.xml中进行配置 。
(2)定义 mapper 接口:
注意 mapper.xml 的文件名和 mapper 的接口名称保持一致,且放在同一个目录


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: