基于MyBatis实现Dao编程
1、建立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> <!-- 配置全局属性 --> <settings> <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 --> <setting name="useGeneratedKeys" value="true" /> <!-- 使用列别名替换列名 默认:true --> <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} --> |
2、在resources下创建mapper包放映射文件SecKillDao.xml和SuccessKilledDao.xml
SecKillDao.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="org.secKill.dao.SecKillDao"> <!-- 目的:为dao接口方法提供sql语句配置 --> <update id="reduceNumber"> <!-- 具体的sql --> UPDATE seckill SET number = number - 1 WHERE seckill_id = #{secKillId} AND start_time <![CDATA[ <= ]]> #{killTime} AND end_time >= #{killTime} AND number > 0 </update> <select id="queryById" resultType="SecKill" parameterType="long"> SELECT seckill_id, NAME, number, start_time, end_time, create_time FROM seckill WHERE seckill_id = #{secKillId} </select> <select id="queryAll" resultType="SecKill"> SELECT seckill_id, NAME, number, start_time, end_time, create_time FROM seckill ORDER BY create_time DESC LIMIT #{offset}, #{limit} </select> <select id="killByProcedure" statementType="CALLABLE"> call execute_seckill ( #{secKillId, jdbcType = BIGINT, mode = IN }, #{phone, jdbcType = BIGINT, mode = IN }, #{killTime, jdbcType = TIMESTAMP, mode = IN }, #{result, jdbcType = INTEGER, mode = OUT } ) </select> </mapper> |
SuccessKilledDao.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="org.secKill.dao.SuccessKilledDao"> <insert id="insertSuccessKilled"> <!-- 主键冲突,报错 --> INSERT ignore INTO success_killed (seckill_id, user_phone, state) VALUES (#{secKillId}, #{userPhone}, 0) </insert> <select id="queryByIdWithSeckill" resultType="SuccessKilled"> <!-- 如何告诉MyBatis把结果映射到SuccessKilled同时映射seckill属性 --> <!-- 可以自由控制SQL --> SELECT sk.seckill_id, sk.user_phone, sk.create_time, sk.state, s.seckill_id "seckill.seckill_id", s.`name` "seckill.name", s.number "seckill.number", s.start_time "seckill.start_time", s.end_time "seckill.end_time", s.create_time "seckill.create_time" FROM success_killed sk INNER JOIN seckill s ON sk.seckill_id = s.seckill_id WHERE sk.seckill_id = #{secKillId} AND sk.user_phone = #{userPhone} </select> </mapper> |
原文地址:https://www.cnblogs.com/sinceForever/p/8454476.html
时间: 2024-10-28 12:35:13