赞
踩
在 Mybatis 中如果使用注解式开发,那么注解需要添加在 Mapper 接口中的抽象方法上,在注解中给定需要执行的 SQL 语句即可,这样就可以不需要映射配置文件。MyBatis 支持纯注解方式,支持纯映射配置文件方式,也支持注解和映射配置文件混合形式。当只有接口没有映射配置文件时在 mybatis-cfg.xml 中对于引入映射可以通过加载指定接口类。也可以使用指定加载的包。
public interface UsersMapper {
@Select("select * from users")
List<Users> selectUsersAll();
}
public class SelectUsersAllTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
List<Users> list = usersMapper.selectUsersAll();
list.forEach(System.out::println);
}
}
//顺序传参法
@Select("select * from users where username = #{param1} and usersex = #{param2}")
List<Users> selectUsersByNameAndSexOrder(String username,String usersex);
@Select("select * from users where username = #{name} and usersex = #{sex}")
List<Users> selectUsersByNameAndSexOrder2(@Param("name") String username, @Param("sex") String usersex);
//POJO传参法
@Select("select * from users where username = #{username} and usersex = #{usersex}")
List<Users> selectUsersByNameAndSexPOJO(Users users);
//Map传参法
@Select("select * from users where username = #{keyname} and usersex = #{keysex}")
List<Users> selectUsersByNameAndSexMap(Map<String ,String >map);
//添加用户
@Insert("insert into users values(default,#{username},#{usersex})")
int insertUsers(Users users);
public class InsertUsers2Test {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
Map<String ,String > map = new HashMap<>();
map.put("name","yiyi");
map.put("sex","famale");
int flag = usersMapper.insertUsers2(map);
System.out.println(flag);
sqlSession.commit();
}
}
@Update("update users set userid = #{id},username = #{name},usersex =#{sex} where username = #{prename}")
int updateUsers2(Map<String,String>map);
public class UpdateUsers2Test {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
Map<String,String> map = new HashMap<>();
map.put("id","3");
map.put("name","nine");
map.put("sex","female");
map.put("prename","kkkkkkkkkkk");
int flag = usersMapper.updateUsers2(map);
System.out.println(flag);
sqlSession.commit();
}
}
@Delete("delete from users where userid in (#{a},#{b})")
int deleteUsers2(@Param("a") int a,@Param("b") int b);
public class DeleteUsers2Test {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
int flag = usersMapper.deleteUsers2(12,17);
System.out.println(flag);
sqlSession.commit();
}
}
在 Mybatis 中的注解开发中,对于动态 SQL 的处理是比较繁琐的,所以如果有动态 SQL的操作,建议使用映射配置文件文件方式实现。
在
//动态SQL查询
@Select("<script>select * from users where 1=1 <if test="username != null and username != ''"> and username = #{username}</if> <if test="usersex != null and usersex != ''">and usersex = #{usersex}</if></script>")
List<Users> selectUsersByProperty(Users users);
public class SelectUsersByPropertyTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
Users users = new Users();
users.setUsername("aaaaaa");
users.setUsersex("male");
List<Users> list = usersMapper.selectUsersByProperty(users);
list.forEach(System.out::println);
}
}
在 MyBatis3 的注解中包含了@SelectProvider、@UpdateProvider、@DeleteProvider、@InsertProvider,这些注解统称为 SqlProvider,它们分别对应着查询、修改、删除、新增操作。当使用这些注解时将不在注解中直接编写 SQL,而是调用某个类的特定方法来生成 SQL。
//在方法中构建SQL
@SelectProvider(type = UsersMapperProvider.class,method = "selectUsersByPropertySQL")
List<Users> selectUsersByPropertyProvider(Users users);
class UsersMapperProvider{
//生成动态SQL
public String selectUsersByPropertySQL(Users users){
StringBuffer sb = new StringBuffer("select * from users where 1=1 ");
if (users.getUsername() != null && users.getUsername() !=""){
sb.append(" and username = #{username}");
}
if (users.getUsersex() != null && users.getUsersex() != ""){
sb.append(" and usersex = #{usersex}");
}
return sb.toString();
}
}
public class SelectUsersByPropertyProviderTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
Users users = new Users();
users.setUsername("aaaaaa");
users.setUsersex("male");
List<Users> list = usersMapper.selectUsersByPropertyProvider(users);
list.forEach(System.out::println);
}
}
在 Mybatis 中的注解开发中,对于结果集的映射处理也是比较繁琐的,所以如果有结果集映射操作,建议使用映射配置文件文件方式实现。
可通过该注复用其他方法上的映射配置
value: 指定其他@Results 的 id 的值。
//结果集映射
@Select("select userid as id,username as name,usersex as sex from users where userid = #{userid}")
@Results(id = "usersMapper" ,value = {
@Result(id = true,property = "userid",column = "id"),
@Result(property = "username",column = "name"),
@Result(property = "usersex",column = "sex")
})
Users selectUsersByIdMapper(int userid);
@Select("select userid as id,username as name,usersex as sex from users where userid = #{userid}")
@ResultMap(value = {"usersMapper"})
Users selectUsersByIdMapper2(int userid);
public class SelectUsersByIdMapperTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
//Users users = usersMapper.selectUsersByIdMapper(1);
Users users = usersMapper.selectUsersByIdMapper2(1);
System.out.println(users);
}
}
在 Mybatis 的注解开发中对于多表查询只支持 N+1 次查询,不支持连接查询。
public class Roles {
private int roleid;
private String rolename;
public int getRoleid() {
return roleid;
}
public void setRoleid(int roleid) {
this.roleid = roleid;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
@Override
public String toString() {
return "Roles{" +
"roleid=" + roleid +
", rolename='" + rolename + ''' +
'}';
}
}
public class Users {
private int userid;
private String username;
private String usersex;
private Roles roles;
public Roles getRoles() {
return roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsersex() {
return usersex;
}
public void setUsersex(String usersex) {
this.usersex = usersex;
}
@Override
public String toString() {
return "Users{" +
"userid=" + userid +
", username='" + username + ''' +
", usersex='" + usersex + ''' +
'}';
}
}
public interface RolesMapper {
@Select("select * from roles where user_id = #{userid}")
Roles selectRolesByUserId(int userid);
}
//一对一的关联查询
@Select("select * from users where userid =#{userid}")
@Results(id = "usersAndRolesMapper",value = {
@Result(id = true,property = "userid",column = "userid"),
@Result(property = "username",column = "username"),
@Result(property = "usersex",column = "usersex"),
@Result(property = "roles",column = "userid",one = @One(select = "com.bjsxt.mapper.RolesMapper.selectRolesByUserId"))
})
Users selectUsersAndRolesByUserId(int userid);
public class SelectUsersAndRolesByUserIdTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
Users users = usersMapper.selectUsersAndRolesByUserId(1);
System.out.println(users);
Roles roles = users.getRoles();
System.out.println(roles);
}
}
public class Orders {
private int orderid;
private double orderprice;
public int getOrderid() {
return orderid;
}
public void setOrderid(int orderid) {
this.orderid = orderid;
}
public double getOrderprice() {
return orderprice;
}
public void setOrderprice(double orderprice) {
this.orderprice = orderprice;
}
@Override
public String toString() {
return "Orders{" +
"orderid=" + orderid +
", orderprice=" + orderprice +
'}';
}
}
public class Users {
private int userid;
private String username;
private String usersex;
private Roles roles;
private List<Orders> orders;
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public Roles getRoles() {
return roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsersex() {
return usersex;
}
public void setUsersex(String usersex) {
this.usersex = usersex;
}
@Override
public String toString() {
return "Users{" +
"userid=" + userid +
", username='" + username + ''' +
", usersex='" + usersex + ''' +
'}';
}
}
public interface OrdersMapper {
@Select("select * from orders where user_id =#{userid}")
List<Orders> selectOrdersByUserId(int userid);
}
//一对多的关联查询
@Select("select * from users where userid = #{userid}")
@Results(id = "usersAndOrdersMapper",value = {
@Result(id = true,property = "userid",column = "userid"),
@Result(property = "username",column = "username"),
@Result(property = "usersex",column = "usersex"),
@Result(property = "orders",column = "userid",many = @Many(select = "com.bjsxt.mapper.OrdersMapper.selectOrdersByUserId",fetchType = FetchType.LAZY))
})
Users selectUsersAndOrdersByUserId(int userid);
public class SelectUsersAndOrdersByUserIdTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
Users users = usersMapper.selectUsersAndOrdersByUserId(1);
System.out.println(users);
List<Orders> list = users.getOrders();
list.forEach(System.out::println);
}
}
结束!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。