CREATE TABLE `users` (
`userid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL, `usersex` varchar(10) DEFAULT NULL, PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
public class Users {
private int userid;
private String username;
private String usersex;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsersex() {
return usersex;
}
public void setUsersex(String usersex) {
this.usersex = usersex;
}
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bjsxt
jdbc.username=root
jdbc.password=mysql
<?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文件-->
<properties resource="db.properties"/>
<!-- 环境的配置-->
<environments default="development">
<environment id="development">
<!-- 配置事务-->
<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>
<!-- 引入映射配置文件-->
<mappers>
<!-- 使用相对路劲方式引入-->
<mapper resource="com/bjsxt/mapper/UsersMapper.xml"/>
</mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.UserMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.UserMapper">
<!-- 查询所有用户-->
<select id="selectUsersAll" resultType="com.bjsxt.pojo.Users">
select * from users;
</select>
</mapper>
public interface UsersDao {
List<Users> selectUsersAll() throws IOException;
}
public class UsersDaoImpl implements UsersDao {
//查询所有用户
@Override
public List<Users> selectUsersAll() throws IOException {
//创建SqlSessionFactory对象
InputStream inputStream = Resources.getResourceAsStream("mybatis-cfg.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过SqlSession对象下的API完成对数据库的操作
List<Users> list = sqlSession.selectList("com.bjsxt.mapper.UserMapper.selectUsersAll");
//关闭SqlSession对象
sqlSession.close();
return list;
}
}
public class Test {
public static void main(String[] args) throws IOException {
UsersDao usersDao = new UsersDaoImpl();
List<Users> list = usersDao.selectUsersAll();
for (Users users:list){
System.out.println(users.getUserid()+"\t"+users.getUsername()+"\t"+users.getUsersex());
}
}
}
<!-- 根据用户ID查询用户-->
<select id="selectUsersById" parameterType="int" resultType="com.bjsxt.pojo.Users">
select * from users where userid = #{userid};
</select>
public interface UsersDao {
List<Users> selectUsersAll() throws IOException;
Users selectUsersById(int userid) throws IOException;
}
//根据用户ID查询用户
@Override
public Users selectUsersById(int userid) throws IOException {
//创建SqlSessionFactory对象
InputStream inputStream = Resources.getResourceAsStream("mybatis-cfg.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过SqlSession对象下的API完成对数据库的操作
Users users = sqlSession.selectOne("com.bjsxt.mapper.UserMapper.selectUsersById",userid);
//关闭SqlSession对象
sqlSession.close();
return users;
}
public class Test {
public static void main(String[] args) throws IOException {
UsersDao usersDao = new UsersDaoImpl();
Users users = usersDao.selectUsersById(1);
System.out.println(users.getUserid()+"\t"+users.getUsername()+"\t"+users.getUsersex());
}
}
在映射配置文件中向 SQL 语句中绑定参数的语法结构为#{ }和${ }。
#{ } 和 ${ }的区别:
#{ } 解析为一个 JDBC 预编译语句(PreparedStatement)的参数标记符占位符 ?。使用该方式可避免 SQL 注入。
$ { } 仅仅为一个纯碎的 String 替换,在 Mybatis 的动态 SQL 解析阶段将会进行变量替换。${ }
在预编译之前已经被变量替换了,这会存在 SQL 注入问题。
#{ } 适用于参数绑定, ${ }适用于动态绑定。
ThreadLocal 提供了线程内存储变量的能力,这些变量不同之处在于每一个线程读取的变量是对应的互相独立的。通过 get 和 set 方法就可以得到当前线程对应的值。
如果多个 DML 操作属于一个事务,因为 commit()和 rollback()都是由 SqlSession 完成的,所以必须保证使用一个 SqlSession。但是多个不同的 DML 操作可能在不同类的不同方法中,每个方法中要单独的获取 SqlSession。比如商城下订单时,其实涉及商品库存变化、订单添加、订单明细添加、付款、日志添加等多个 DML 操作,分布在不同类中。
如何在多个 DML 操作之间使用同一个 SqlSession 呢,可以使用 ThreadLocal 来存储。保证一个线程中的操作使用的都是一个 SqlSession。
在 Web 项目中用户的每次请求会启动一个新的线程,比如点击”结算”完成购物车结算。在 Java 项目中每次启动 main()也会自动开启一个 main 线程。
//Mybatis工具类
public class MybatisUtils {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
private static SqlSessionFactory sqlSessionFactory = null;
static {
//创建SqlSessionFactory
InputStream is = null;
try{
is = Resources.getResourceAsStream("mybatis-cfg.xml");
}catch (IOException e){
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}
//获取SqlSession
public static SqlSession getSqlSession(){
SqlSession sqlSession = threadLocal.get();
if (sqlSession == null){
sqlSession = sqlSessionFactory.openSession();
threadLocal.set(sqlSession);
}
return sqlSession;
}
//关闭SqlSession
public static void closeSqlSession(){
SqlSession sqlSession = threadLocal.get();
if (sqlSession != null){
sqlSession.close();
threadLocal.set(null);
}
}
}
<!-- 添加用户-->
<insert id="insertUsers">
insert into users value (default ,#{username},#{usersex})
</insert>
public interface UsersDao {
List<Users> selectUsersAll() throws IOException;
Users selectUsersById(int userid) throws IOException;
void insertUsers(Users users);
}
// 添加用户
@Override
public void insertUsers(Users users) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
sqlSession.insert("com.bjsxt.mapper.UserMapper.insertUsers",users);
}
public interface UsersService {
void addUsers(Users users);
}
public class UsersServiceImpl implements UsersService {
//添加用户
@Override
public void addUsers(Users users) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UsersDao usersDao = new UsersDaoImpl();
usersDao.insertUsers(users);
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
MybatisUtils.closeSqlSession();
}
}
}
public class AddUserTest {
public static void main(String[] args) {
UsersService usersService = new UsersServiceImpl();
Users users = new Users();
users.setUsername("zhangsan");
users.setUsersex("male");
usersService.addUsers(users);
}
}
<!-- 预更新用户的查询-->
<select id="selectUsersById2" resultType="com.bjsxt.pojo.Users">
select * from users where userid = ${userid}
</select>
<!-- 更新用户操作-->
<update id="updateUsersById">
update users set username = #{username},usersex = #{usersex} where userid = #{userid}
</update>
public interface UsersDao {
List<Users> selectUsersAll() throws IOException;
Users selectUsersById(int userid) throws IOException;
void insertUsers(Users users);
Users selectUsersById2(int userid);
void updateUsersById(Users users);
}
//预更新用户的查询
@Override
public Users selectUsersById2(int userid) {
SqlSession sqlsession = MybatisUtils.getSqlSession();
Users users = sqlsession.selectOne("com.bjsxt.mapper.UserMapper.selectUsersById2",userid);
return users;
}
//更新用户
@Override
public void updateUsersById(Users users) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
sqlSession.update("com.bjsxt.mapper.UserMapper.updateUsersById",users);
}
//创建UsersService业务层接口
public interface UsersService {
void addUsers(Users users);
Users preUpdateUsers(int userid);
void modifyUsers(Users users);
}
//预更新用户
@Override
public Users preUpdateUsers(int userid) {
Users users = null;
try{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersDao usersDao = new UsersDaoImpl();
users = usersDao.selectUsersById2(userid);
}catch (Exception e){
e.printStackTrace();
}finally {
MybatisUtils.closeSqlSession();
}
return users;
}
//更新用户
@Override
public void modifyUsers(Users users) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UsersDao usersDao = new UsersDaoImpl();
usersDao.updateUsersById(users);
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
MybatisUtils.closeSqlSession();
}
}
//更新用户测试
public class UpdateUsersTest {
public static void main(String[] args) {
UsersService usersService = new UsersServiceImpl();
Users users = usersService.preUpdateUsers(1);
System.out.println(users.getUserid());
users.setUsername("COREY");
users.setUsersex("MALE");
usersService.modifyUsers(users);
}
}
<!-- 根据用户ID删除用户-->
<delete id="deleteUsersById">
delete from users where userid = #{userid}
</delete>
public interface UsersDao {
List<Users> selectUsersAll() throws IOException;
Users selectUsersById(int userid) throws IOException;
void insertUsers(Users users);
Users selectUsersById2(int userid);
void updateUsersById(Users users);
void deleteUsersById(int userid);
}
//删除用户
@Override
public void deleteUsersById(int userid) {
SqlSession sqlSession =MybatisUtils.getSqlSession();
sqlSession.delete("com.bjsxt.mapper.UserMapper.deleteUsersById",userid);
}
//创建UsersService业务层接口
public interface UsersService {
void addUsers(Users users);
Users preUpdateUsers(int userid);
void modifyUsers(Users users);
void dropUsersById(int userid);
}
//删除用户
@Override
public void dropUsersById(int userid) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
UsersDao usersDao = new UsersDaoImpl();
usersDao.deleteUsersById(userid);
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
MybatisUtils.closeSqlSession();
}
}
//删除用户
public class DeleteUsersTest {
public static void main(String[] args) {
UsersService usersService = new UsersServiceImpl();
usersService.dropUsersById(3);
}