MyBatis注解位于org.apache.ibatis.annotations包下,常用注解如下
1 select 映射查询sql语句 2 insert 映射插入语句 3 update 映射更新语句 4 delete 映射删除语句 5 result 在列和属性之间的单独结果映射,属性包括id column one many,等 id是一个布尔值,表示是否用于主键映射,one是单独的联系和xml中<association>相似 ,mang对集合而言,和xml中的<collection>相似 4 results 多个结果映射(result)列表 。 5 optins提供配置选项的附加值,在映射语句上作为附加功能配置出现。6
当映射方法需要多个参数时,应用于映射器方法参数来给每个参数娶一个名字,否则多参数将会以他们的顺序位置和SQL语句的表达式进行映射
注解使用 @select @insert @update @delete 可以完成常见的增删改查功能sql语句映射
public interface AUserMapper {
@Insert("INSERT INTO USER(username,sex, birthday, address) VALUES(#{username},#{sex},#{birthday},#{address})")
@Options(useGeneratedKeys=true, keyProperty="id")
int saveUser(User user);
@Delete("delete from user where id=#{id}")
int removeUser(@Param("id") Integer id);
@Update("update user set username=#{username}, birthday=#{birthday}, sex=#{sex}, address=#{address} where id=#{id}")
void modifyUser(User user);
@Select("select * from user where id=#{id}")
@Results({
@Result(id=true, column="id", property="id"),
@Result(column="username", property="username"),
@Result(column="birthday", property="birthday"),
@Result(column="sex", property="sex"),
@Result(column="address", property="address"),
})
User selectUserById(Integer id);
@Select("select * from user")
List<User> selectAllUser();
}
@Test
public void saveUserTest() throws Exception{
//读取配置文件
//全局配置文件的路径
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//调用SqlSession的增删改查方法
//第一个参数:表示statement的唯一标示
AUserMapper mapper = sqlSession.getMapper(AUserMapper.class);
User user = new User();
user.setUsername("whe");
user.setSex("i");
user.setAddress("ds");
mapper.saveUser(user);
System.out.println(user.getId());
sqlSession.close();
}
一对一 一个订单只有一个用户
public interface UserMapper {
@Select("select * from user where id=#{id}")
User selectUserById(Integer id);
}
public interface OrderMapper {
@Select("select * from orders where id=#{id}")
@Results({
@Result(id=true, column="id", property="id"),
@Result(column="number", property="number"),
@Result(column="createtime", property="createtime"),
@Result(column="note", property="note"),
@Result(column="user_id", property="user",
one =@One(select="com.itheima.ms.mapper.UserMapper.selectUserById",
fetchType=FetchType.EAGER))
})
Orders selectOrdersById(Integer id);
}
MyBatis 注解支持动态SQL , @selectprovider @insertprovider @updateprovider @deleteprovider 来帮助构建动态sql语句,org.apache.ibatis.jdbc.SQL用来拼接sql语句,Privoder方方法可接收ava对象,map对象
@SelectProvider(type=com.itheima.ms.mapper.UserSqlPrivoder.class, method="selectWithPar")
List <User> selectUserById(Map<String, Object> map);
public class UserSqlPrivoder {
public String selectWithPar(final Map<String, Object> map){
return new SQL(){
{
SELECT("*");
FROM("user");
if (map.get("id") != null){
WHERE(" id=#{id}");
}
}
}.toString();
}
}