MyBatis 常规方法使用
1. 没有使用接口编程,Java是面向接口编程语言。应该对数据库操作定义一些接口,调用dao接口完成数据库操作。
public interface UserDao {
//根据Id查询用户信息
public User findUserById(int userId) throws Exception;
//添加用户
public void insertUser(User user) throws Exception;
//修改用户
public void updateUser(User user) throws Exception;
//删除用户
public void deleteUser(int userId) throws Exception;
}
public class UserDaoImpl implements UserDao {
private SqlSessionFactory sqlSessionFactory;
//通过spring将 SqlSessionFactory 注入,这里没有spring,暂时使用构造方法代替
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.setSqlSessionFactory(sqlSessionFactory);
}
@Override
public User findUserById(int userId) throws Exception {
SqlSession sqlSession = null;
User user = null;
try {
//通过SqlSessionFactory获取SqlSession
sqlSession = sqlSessionFactory.openSession();
//使用session操作数据库
//selectOne第一个参数:指定sql的id(statement id),注意带上namespace;第二个参数:向sql中传的参数值
user = sqlSession.selectOne("test.findUserById", userId);
System.out.println(user);
} catch (Exception e) {
// TODO: handle exception
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return user;
}
@Override
public void insertUser(User user) throws Exception {
SqlSession sqlSession = null;
try {
//通过SqlSessionFactory获取SqlSession
sqlSession = sqlSessionFactory.openSession();
//使用session操作数据库
sqlSession.insert("test.insertUser", user);
//提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}