很好玩的一种注解开发
通过使用注解开发
1.省去了mybatis的配置文件中对实体和mapper.xml文件的配置
<!--配置实体-->
<!-- <property name="typeAliasesPackage" value="com.blueocean.saveme.entity"/>-->
<!--配置mapper.xml文件-->
<!-- <property name="mapperLocations" value="classpath:com/blueocean/saveme/mapper/*.xml"/>-->
2.自然也就省去了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.blueocean.saveme.mapper.NameMapper">
<!--<resultMap id="BaseResultMap" type="com.blueocean.saveme.entity.NameBean">
<result column="int_id" property="id" jdbcType="INTEGER"/>
<result column="vc_name" property="name" jdbcType="VARCHAR"/>
<result column="int_age" property="age" jdbcType="INTEGER"/>
<result column="dat_create_time" property="createTime" jdbcType="TIMESTAMP"/>
<result column="int_status" property="status" jdbcType="INTEGER"/>
</resultMap>-->
<!--<insert id="insert" parameterType="com.blueocean.saveme.entity.NameBean" useGeneratedKeys="true" keyProperty="id">
insert into name(
vc_name,
int_age,
dat_create_time,
int_status
)values(
#{name,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER},
SYSDATE(),
1
)
</insert>-->
<!--<select id="selectById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select * from name where int_id = #{id,jdbcType=INTEGER}
</select>-->
<!-- <select id="getAll" resultMap="BaseResultMap">
select * from name
</select>-->
</mapper>
而进行注解开发的方式又十分的简单,只需要在mapper接口出进行处理,下面进入正题
(注:注解内的sql语句大小写均可)
1.插入对象,并将主键的值返回
@Insert("INSERT INTO name (vc_name,int_age) VALUES(#{name},#{age})")
//返回主键的值
@Options(useGeneratedKeys = true,keyProperty = "id")
int insert(NameBean bean);
2.单个查询,返回一个对象,完成实体与数据表中字段的映射关系
(注:使用id="BaseResultMap"是为了方便其他查询方法的复用,若不需要,可以不写)
@Select("select * from name where int_id = #{id}")
@Results(id="BaseResultMap",value=
{
@Result(column = "int_id" ,property = "id"),
@Result(column = "vc_name",property = "name"),
@Result(column = "int_age",property = "age"),
@Result(column = "dat_create_time",property = "createTime"),
@Result(column = "int_status",property = "status")
}
)
NameBean selectById(Integer id);
3.查询多个,返回list,容器内装的对象
@Select("select * from name")
@ResultMap("BaseResultMap")
List<NameBean> getAll();
至此大功告成,调用方法与使用mapper.xml文件方法一致