1、CRUD
咱们能够在工具类创立的时候实现主动提交事务!
public class MybatisUtils{
private static SqlSessionFactory sqlSessionFactory;
static{
try{
//应用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(IOException e){
e.printStackTrace();
}
}
public static sqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
2.编写接口
public interface UserMapper{
@Select("select * from user")
List<User> getUsers();
@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id);
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
@Delete(delete from user where id=#{uid})
int deleteUser(@Param("uid") int id);
}
3.编写外围配置文件
<mappers>
<mapper class="com.jialidun.dao.UserDao"/>
</mappers>
【留神:咱们必须要将接口注册绑定到咱们的外围配置文件中!】
对于@Param(“xxx”)注解
- 根本类型的参数或者String类型,须要加上
- 援用类型不须要加
- 如果只有一个根本类型的话,能够疏忽,然而倡议加上!
- 咱们在SQL中援用的就是@Param(“xxx”)中设定的属性名!
#{}和${}的区别
- #{}示意一个占位符号,通过#{}能够实现preparedStatement向占位符中设置值,主动
进行java类型和jdbc类型转换。
- #{}能够无效避免sql注入。
- #{}能够接管简略类型值或pojo属性值。 如果parameterType传输单个简略类型值,#{}括号中能够是value或其它名称。
- ${}示意拼接sql串,通过${}能够将parameterType 传入的内容拼接在sql中且不进行
jdbc类型转换
- ${}能够接管简略类型值或pojo属性值,如果parameterType传输单个简略类型值,${}括号中只能是value。
发表回复