mybatis-普通sq增删改查学习笔记
import java.util.*;
import cn.mybatis.entity.Student;
import cn.mybatis.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
public class StudentDao {
/**
* 增加学生
*/
public void add(Student student) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
//事务开始(默认)
//读取StudentMapper.xml映射文件中的SQL语句
int i = sqlSession.insert(Student.class.getName()+".add",student);
System.out.println("本次操作影响了"+i+"行");
//事务提交
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
sqlSession.rollback();
throw e;
}finally{
//MybatisUtil.closeSqlSession();
}
}
/**
* 根据ID查询学生
*/
public Student findById(int id) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
Student student = sqlSession.selectOne(Student.class.getName()+".findById",id);
sqlSession.commit();
return student;
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
/**
* 查询所有学生
*/
public List findAll() throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
return sqlSession.selectList(Student.class.getName()+".findAll");
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
/**
* 更新学生
*/
public void update(Student student) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
sqlSession.update(Student.class.getName()+".update",student);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
/**
* 删除学生
*/
public void delete(Student student) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
sqlSession.delete(Student.class.getName()+".delete",student);
//事务
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
// 回滚
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
public static void main(String[] args) throws Exception {
StudentDao dao = new StudentDao();
// dao.add(new Student(3,"美丽",70030.3));
// dao.add(new Student(4,"加油",70030.3));
// dao.add(new Student(5,"关系",70030.3));
// dao.add(new Student(6,"规律",70030.3));
// dao.add(new Student(7,"古蔺",70030.3));
// List studentslist = dao.findAll();
// for (Student student : studentslist ) {
// System.out.print(student.getId()+":"+student.getName()+":"+student.getSal());
// }
// Student student = dao.findById(4);
// student.setName("liwen");
// dao.update(student);
}
}
insert into students(id,name,sal) values(#{id},#{name},#{sal})
update students set name=#{name},sal=#{sal} where id=#{id}
delete from students where id = #{id}
网站题目:mybatis-普通sq增删改查学习笔记
文章分享:http://myzitong.com/article/ihjdod.html