注解查询
环境搭建,不用IUserDao.xml,其他都一样
User实体类
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
主配置xml
<?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>
<!--引入外部配置文件-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置别名-->
<typeAliases>
<package name="sise.cn.domain"/>
</typeAliases>
<!--配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入指定带有注解的dao接口所在-->
<mappers>
<package name="sise.cn.dao"/>
</mappers>
</configuration>
IUserDao实体类,并且用注解查询
/**
*在mybatis中针对,CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
}
test:
public static void main(String[] args) throws IOException {
//1.读取配置文件,生成字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSeesion对象
SqlSession sqlSession = factory.openSession();
//4.获取dao的代理对象
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
//5.执行查询所有方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
//6.释放资源
sqlSession.close();
in.close();
}
注解保存和更新
保存
IuserDao:
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
test:
@Test
public void testsave(){
User user = new User();
user.setUsername("666ms");
user.setAddress("广州");
userDao.saveUser(user);
}
更新
/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},address=#{address},birthday=#{birthday} where id=#{id}")
void updateUser(User user);
@Test
public void update(){
User user = new User();
user.setId(50);
user.setUsername("666");
user.setSex("男");
userDao.updateUser(user);
}
删除
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id}")
void deletUser(Integer userId);
模糊查询
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id}")
void deletUser(Integer userId);
test:
@Test
public void test(){
List<User> users = userDao.findUserByName("%王%");
for (User user : users) {
System.out.println(user);
}
}