Mybatis[一]基本语法
1. 单参数
基本类型
select语句为例:
接口映射文件UserMapper.xml:
<select id="findUserByID" resultType="User">
SELECT * FROM user where id=#{id} ;
</select>
select 标签中
id:接口方法名
resultType: 自动转换的对象:需要属性和数据库中的列名一致.
如果不一样需要手动转换:resultMap
- 参数占位符:
1)#{}:执行SQL时,会将#{}占位符替换为?,将来自动设置参数值
2)${}:拼SQL。会存在SQL注入问题 - parameterType:
用于设置参数类型,该参数可以省略 - SQL语句中特殊字符处理:
转义字符
<![CDATA[ 内容 ]]>:CD提示
接口文件 (Interface) UserMapper.java
/**
*通过用户ID查询信息:单表查询
* @param id 用户ID
*/
public interface UserMapper {
User findUserByID(int id);
}
test:
public static void main(String[] args) {
try {
//加载MyBatis配置文件
String s="mybatis-config.xml";
InputStream resourceAsStream = Resources.getResourceAsStream(s);
//链接池
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取链接,设置自动提交
SqlSession sqlSession = sessionFactory.openSession(true);
//反射调用
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userByID = mapper.findUserByID(1);
//打印结果
System.out.println(userByID);
} catch (IOException e) {
e.printStackTrace();
}
2. 多参数
参数接收:
- 散装参数: 如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)
- 对象参数: 对象的属性名称要和参数占位符名称一致
- Map集合参数: Map的键要和占位符名称一致
散装参数,Map参数,对象参数:
UserMapper.xml
<select id="selectByCondition" resultType="User">
select * from user where username=#{username} and sex=#{sex};
</select>
接口文件 UserMapper.java
/**
* 多参数
* @param username 用户名
* @param sex 性别
*/
List<User> selectByCondition(@Param("username") String username,@Param("sex") String sex);
List<User> selectByCondition(User user);
List<User> selectByCondition(Map map);
test文件
@Test
public void findUserByConditions(){
UserMapper mapper = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true).getMapper(UserMapper.class);
List<User> users = mapper.selectByCondition("孙大空", "男");
for (User user : users) {
System.out.println(user);
}
}
@Test
public void findUserByConditionsByMap(){
UserMapper mapper = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true).getMapper(UserMapper.class);
HashMap<String, String> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.put("username","孙大空");
objectObjectHashMap.put("sex","男");
List<User> users = mapper.selectByCondition(objectObjectHashMap);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void findUserByConditionsByUser(){
User user = new User(null, "孙大空", null, "男", null);
UserMapper mapper = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true).getMapper(UserMapper.class);
List<User> users = mapper.selectByCondition(user);
for (User user1 : users) {
System.out.println(user1);
}
}