第一步,先写一个pojo类
package com.iss.student;
import java.util.Date;
import java.util.List;
public class Student {
private Integer id;
private String class_id;
private String name;
private String sex;
private Date birthday;
private Float weight;
private Double height;
private String addr;
private String phone;
private Date ruxue_time;
private String xue_qi;
public void setId(Integer id) {
this.id = id;
}
public void setClass_id(String class_id) {
this.class_id = class_id;
}
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setWeight(Float weight) {
this.weight = weight;
}
public void setHeight(Double height) {
this.height = height;
}
public void setAddr(String addr) {
this.addr = addr;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setRuxue_time(Date ruxue_time) {
this.ruxue_time = ruxue_time;
}
public void setXue_qi(String xue_qi) {
this.xue_qi = xue_qi;
}
public Integer getId() {
return id;
}
public String getClass_id() {
return class_id;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public Date getBirthday() {
return birthday;
}
public Float getWeight() {
return weight;
}
public Double getHeight() {
return height;
}
public String getAddr() {
return addr;
}
public String getPhone() {
return phone;
}
public Date getRuxue_time() {
return ruxue_time;
}
public String getXue_qi() {
return xue_qi;
}
public Student() {
// TODO Auto-generated constructor stub
}
public Student( String class_id, String name, String sex,
Date birthday, Float weight, Double height, String addr,
String phone, Date ruxue_time, String xue_qi) {
super();
this.class_id = class_id;
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.weight = weight;
this.height = height;
this.addr = addr;
this.phone = phone;
this.ruxue_time = ruxue_time;
this.xue_qi = xue_qi;
}
}
第二步,写一个接口,定义增删改查
package com.iss.student;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface IMapperStudentDAO {
@Select("select * from Student") //这个注解表示搜索所有的记录
List search();
@Insert("insert into student values(null,#{class_id},#{name},#{sex},#{birthday},#{weight},#{height},#{addr},#{phone},#{ruxue_time},#{xue_qi})")
//这个注解里的sql语句表示添加一条数据,#(这里的字段是pojo对应的字段),null是因为我数据库里主键是自增的
int insert(Student student);
@Select("select * from student where id=#{id}")
//这个注解表示搜索所有的记录
Student search2(Integer id);@Update("update student set name=#{name} where id=#{id}")
//这个注解表示搜索一条记录
int update(Student student);@Delete("delete from student where id=#{id}") //这个注解表示删除一条记录
package com.iss.mybatis;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
*
* 作者:南航
*2017年11月2日,上午11:05:47
*/
public class MyBatisSessionFactory {//ctrl+shift+o:引入所有工具类
public static SqlSession getSession(){
try {
String resource = "mybatis.cfg.xml"; //表示为:src/mybatis.cfg.xml
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = ssf.openSession();
return session;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//表示配置文件可以在任何其他目录下
public static SqlSession getSession(String resource){
try {
// String resource = "mybatis.cfg.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = ssf.openSession();
return session;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
package com.iss.student;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.iss.mybatis.MyBatisSessionFactory;
public class StudentDAO { //这个接口是mybatis自动实现的,不需要手工implements,而且,这个DAO下面的方法可以与接口里的方法不一样,就比如下面的删除
public List search() {
// TODO Auto-generated method stub
List l=null;
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class); //就是通过这行代码获取mybatis进行增删改查的Dao
l=dao.search();
return l;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
s.close();
}
}
public int insert(Student student){
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
int n=dao.insert(student);
s.commit(); //所谓的事务,是关乎增删改,对数据进行操作的sql,因此查询语句除外,都需要提交操作(commit)
return n;
} catch (Exception e) {
e.printStackTrace();
s.rollback();
return -1;
}finally{
s.close();
}
}
public Student search(Integer id) {
// TODO Auto-generated method stub
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
Student student=dao.search2(id); //在接口不识别方法重载,所以我在这里定义成了search2
return student;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
s.close();
}
}
public int update(Student student){
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
int n=dao.update(student);
s.commit();
return n;
} catch (Exception e) {
// TODO: handle exception
s.rollback();
return -1;
}finally{
s.close();
}
}
public int delete(Integer [] ids){ //这里就证明了接口和实现类的方法可以不一样,我接口里定义的是Integer,而这里定义的是数组
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
int m=0;
for (int i = 0; i < ids.length; i++) {
int n=dao.delete(ids[i]);
m=m+n;
}
s.commit();
return m;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
s.rollback();
return 0;
}finally{
s.close();
}
}
}
package com.iss.student;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.iss.mybatis.MyBatisSessionFactory;
public class StudentDAO {
public List search() {
// TODO Auto-generated method stub
List l=null;
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
l=dao.search();
return l;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
s.close();
}
}
public int insert(Student student){
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
int n=dao.insert(student);
s.commit();
return n;
} catch (Exception e) {
e.printStackTrace();
s.rollback();
return -1;
}finally{
s.close();
}
}
public Student search(Integer id) {
// TODO Auto-generated method stub
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
Student student=dao.search2(id);
return student;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
s.close();
}
}
public int update(Student student){
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
int n=dao.update(student);
s.commit();
return n;
} catch (Exception e) {
// TODO: handle exception
s.rollback();
return -1;
}finally{
s.close();
}
}
public int delete(Integer [] ids){
SqlSession s=null;
try {
s=MyBatisSessionFactory.getSession();
IMapperStudentDAO dao=s.getMapper(IMapperStudentDAO.class);
int m=0;
for (int i = 0; i < ids.length; i++) {
int n=dao.delete(ids[i]);
m=m+n;
}
s.commit(); //写在这里和上面都是一样的,返回的都是成功的记录数
return m;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
s.rollback();
return 0;
}finally{
s.close();
}
}
}
//这是配置数据源
第五步,检测上面的增删改查
package com.iss.student;
import java.util.Date;
public class Test {
static StudentDAO dao=new StudentDAO();
public static void main2(String[] args) {
System.out.println(dao.search().size());
}
public static void main3(String[] args) {
//Student student=new Student("QH10001","南航2","女",new Date(94,9,11),(float) 45,1.79,"湖北第二师范","159951",new Date(04,9,11),"1");
Student student=new Student();
System.out.println(dao.insert(student));
}
public static void main4(String[] args) {
System.out.println(dao.search(10000).getName());
}
public static void main5(String[] args) {
Student student=new Student();
student.setId(10000);
student.setName("南航");
dao.update(student);
}
public static void main(String[] args) {
Integer [] ids={10007,15};
System.out.println(dao.delete(ids));
}
}
下面贴出自己的这个单表的sql,用的是Navicat转成的sql文件
/*
Navicat MySQL Data Transfer
Source Server : nanhang
Source Server Version : 50626
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Target Server Version : 50626
File Encoding : 65001
Date: 2017-11-20 22:04:36
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`CLASS_ID` char(7) DEFAULT NULL,
`NAME` varchar(20) DEFAULT NULL,
`SEX` char(1) DEFAULT NULL,
`BIRTHDAy` datetime DEFAULT NULL,
`WEIGHT` double DEFAULT NULL,
`HEIGHT` decimal(5,4) DEFAULT NULL,
`ADDR` varchar(50) DEFAULT NULL,
`PHONE` char(8) DEFAULT NULL,
`RUXUE_TIME` datetime DEFAULT NULL,
`XUE_QI` char(1) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10116 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('10009', 'QH10001', '李国庆', '男', '1991-01-24 00:00:00', '78.345679234', '1.7893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10010', 'QH10003', '王加明', '女', '1992-07-24 00:00:00', '56.345679234', '1.6893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10011', 'QH10002', '孙爱平', '女', '1993-08-24 00:00:00', '49.345679234', '1.5893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10012', 'QH10003', '张飞翔', '女', '1994-08-24 00:00:00', '51.345679234', '1.6893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10013', 'QH10001', '李小平', '男', '1996-06-24 00:00:00', '78.345679234', '1.7893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10014', 'QH10001', '周晓波', '男', '1997-04-24 00:00:00', '78.345679234', '1.7893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10015', 'QH10001', '王成成', '女', '1996-08-24 00:00:00', '52.345679234', '1.6893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10100', 'QH10001', '李晓强', '男', '1992-03-24 00:00:00', '78.345679234', '1.7893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10108', 'QH10002', '王爱玲', '女', '1996-11-24 00:00:00', '49.345679234', '1.6935', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10109', 'QH10001', '屈红梅', '女', '1995-05-24 00:00:00', '52.345679234', '1.5893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10110', 'QH10001', '成强兵', '男', '1993-01-24 00:00:00', '78.345679234', '1.7893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10111', 'QH10001', '刘天一', '男', '1991-09-24 00:00:00', '78.345679234', '1.7893', '西城区西直门', '8562345', '2008-01-19 00:00:00', '1');
INSERT INTO `student` VALUES ('10113', 'QH10001', '南航', '女', '1994-10-11 00:00:00', '45', '1.7900', '湖北第二师范', '159951', '1904-10-11 00:00:00', '1');
INSERT INTO `student` VALUES ('10114', 'QH10001', '南航2', '女', '1994-10-11 00:00:00', '45', '1.7900', '湖北第二师范', '159951', '1904-10-11 00:00:00', '1');
INSERT INTO `student` VALUES ('10115', null, null, null, null, null, null, null, null, null, null);
总结:Mybatis的注解实现增删改查是高级应用了,因为框架这个东西毕竟是工具,可以简化我们的工作,然而最开始的时候,我们需要做各种尝试,当我们熟练掌握用法后,
就会大大的加快开发速度。