public class User implements Serializable{
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//getter和setter和toString方法已略
}
创建dao包UserDao.java
public interface UserDao {
//传递2个条件或者多个条件,使用@Param注解获取传递数据的对应值,注意value的值必须有传递的参数名相同
@Select(value = "select * from user where username like #{name} and sex = #{sex}")
List<User> findByNameAndSex(@Param(value = "name") String username,@Param(value = "sex") String sex);
//使用map集合传递值
@Select(value = "select * from user where username like #{name} and sex = #{sex}")
List<User> findByNameAndSex2(Map map);
//使用user对象传递数据,直接在#{}中括号内写user对象的变量名
@Select(value = "select * from user where username like #{username} and sex = #{sex}")
List<User> findByUserNameAndSex(User user);
}
创建测试类TestAnnotation.java
public class TestAnnotation{
InputStream is = null;
SqlSession sqlSession = null;
UserDao userDao = null;
AccountDao accountDao = null;
@Before
public void init() throws IOException {
// 1:加载配置文件和映射文件(读取InputStream)
is = Resources.getResourceAsStream("sqlMapConfig.xml");
// 2:获取SqlSessionFactory(相当于DataSource)
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3:获取SqlSession(相当于Connection)
sqlSession = sqlSessionFactory.openSession();
// 4:使用SqlSession获取UserDao(代理)
userDao = sqlSession.getMapper(UserDao.class);
accountDao = sqlSession.getMapper(AccountDao.class);
}
@After
public void destory() throws IOException {
is.close();
//sqlSession.close();
sqlSession.commit();
}
@Test //方案1:使用变量传递参数
public void testfindByNameAndSex(){
String username = "%王%";
String sex = "女";
List<User> list = userDao.findByNameAndSex(username, sex);
for (User user : list) {
System.out.println(user);
}
}
@Test //方案2:使用user对象传递参数
public void testByUserNameAndSex(){
String username = "%王%";
String sex = "女";
User user = new User();
user.setUsername(username);
user.setSex(sex);
List<User> list = userDao.findByUserNameAndSex(user);
for (User user1 : list) {
System.out.println(user1);
}
}
@Test//方案3:使用map集合封装数据实现
public void findByMapNameAndSex(){
String username = "%王%";
String sex = "女";
Map<String,Object> map = new HashMap<String ,Object>();
map.put("name",username);
map.put("sex",sex);
List<User> list = userDao.findByNameAndSex2(map);
for (User user : list) {
System.out.println(user);
}
}
}