myBatis-02 注解方式
注解方式使用MyBatis,在一些单表操作或者业务逻辑简单的系统应用中可以采用基于注解方式类完成CRUD操作。
和09 myBatis-01的代码基本类似,主要少了Mapper文件,myBais主配置文件内有差异,接口来内部包含注解
0、项目文件结构

1、pom.xml配置
同09 myBatis-01
2、Mybatis主配置文件
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://47.100.229.xxx:3306/springStudy?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="xxxx"/>
</dataSource>
</environment>
</environments>
<!-- 引入表的接口类 -->
<mappers>
<mapper class="db.Dao.EmployeeDao" />
</mappers>
</configuration>
3、单个表对应的内容
3.1、模型类
同09 myBatis-01
3.2、数据接口类
每个方法上边通过注解指定相关的Sql语句
package db.Dao;
import db.Domain.Employee;
import org.apache.ibatis.annotations.*;
import java.util.List;
//数据访问接口 - 注解方式
public interface EmployeeDao {
//查询单个对象,单个参数时@Param可以省略
@Select(" select * from Employee where emplId=#{emplId} ")
public Employee queryByEmplId(@Param("emplId") String empId);
//查询多个对象,多个参数时需要通过@Param声明
@Select(" select * from Employee where salary BETWEEN #{start} and #{end} ")
public List<Employee> queryListBySalary(@Param("start") int start, @Param("end") int end);
//新增数据
@Insert(" insert into employee(emplId,`name`,gender,hireDate,salary) values(#{emplId},#{name},#{gender},#{hireDate},#{salary}) ")
public int insert(Employee emp);
//更新数据
@Update(" update employee set `name`=#{name},gender=#{gender},salary=#{salary} where emplId=#{emplId} ")
public int update(Employee emp);
//删除数据
@Delete(" delete from employee where emplId=#{emplId} ")
public void delete(@Param("emplId") String empId);
}
3.3、Mapper文件
无需提供
3.4、主配置文件引用Mapper文件
通过Class引用接口类

3.5、测试代码
同09 myBatis-01

浙公网安备 33010602011771号