MyBatis的纯注解开发
程序员文章站
2022-07-13 11:38:48
...
MyBatis的纯注解方式:
不用写实体类的配置文件,直接在接口里面写
实体类中:User.xml
public class User {
private Integer uid;
private String uname;
private String pass;
//get,set方法,tostring方法和构造方法
}
然后就不需要配置文件,在接口中写
UserMapper
public interface UserMapper {
//查询全部的方法,直接Select("SQL语句")
@Select("select * from user")
public List<User> findAllUser();
//新增 Insert("新增的SQL语句")
@Insert("insert into user values(null,#{uname},#{pass})")
public int addUser(User user);
//删除 Delete("删除的SQL语句")
@Delete("delete from user where uid=#{uid}")
public int deleteUserById(int uid);
//修改 Update("修改的SQL语句")
@Update("update user set uname=#{uname},pass=#{pass} where uid=#{uid}")
public int updateUserById(User user);
}
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>
<!--给包取别名-->
<typeAliases>
<package name="com.ywy.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--接口的注册-->
<!--之前是配置实体类的映射文件,现在没有了,直接配置接口-->
<mappers>
<package name="com.ywy.mapper"/>
</mappers>
</configuration>
测试类
UserMapper umapper=session.getMapper(UserMapper.class);
//直接调用接口的方法
//查询全部
List<User> list = umapper.findAllUser();
for (User user : list) {
System.out.println(user);
}
//新增
int i = umapper.addUser(new User("小明", "12345678"));
System.out.println(i);
//删除
int i2 = umapper.deleteUserById(2);
System.out.println(i2);
//修改
User u=new User("xxxxx","1111111");
u.setUid(3);
int i = umapper.updateUserById(u);
System.out.println(i);