一,前期准备
1. 由于本示例是利用mysql数据库对数据的操作,所以需要提前安装好mysql数据库
2. mybatics jar包下载
进入网址 http://www.mybatis.org/mybatis-3/zh/getting-started.html 下载相关jar包,如图所示 点击mybatics-x.x.x.jar即可下载
3.在数据库中建表
sql语句如下
CREATE DATABASE`test`;
USE `test`;
CREATE TABLE `classes` (
`cid` INT(10) NOT NULL AUTO_INCREMENT,
`cname` VARCHAR(20),
PRIMARY KEY (`cid`)
);
INSERT INTO `test`.`classes` (`cid`, `cname`) VALUES ('1001', 'YC01');
INSERT INTO `test`.`classes` (`cid`, `cname`) VALUES ('1002', 'YC02');
INSERT INTO `test`.`classes` (`cid`, `cname`) VALUES ('1003', 'YC03');
CREATE TABLE `student` (
`sid` INT(10) NOT NULL AUTO_INCREMENT,
`sname` VARCHAR(20),
`age` INT(4),
`email` VARCHAR(50),
`tid` INT(10),
`cid` INT(10),
PRIMARY KEY (`sid`)
);
INSERT INTO `test`.`student` (`sid`, `sname`, `age`, `email`, `tid`, `cid`) VALUES ('100001', '张三', '17', '123@qq.com', '1001', '1001');
INSERT INTO `test`.`student` (`sid`, `sname`, `age`, `email`, `tid`, `cid`) VALUES ('10002', '李四', '16', '456@qq.com', '1001', '1001');
INSERT INTO `test`.`student` (`sid`, `sname`, `age`, `email`, `tid`, `cid`) VALUES ('10003', '王五', '17', 'abc@qq.com', '1002', '1002');
CREATE TABLE `teacher` (
`tid` INT(10) NOT NULL AUTO_INCREMENT,
`tname` VARCHAR(20),
PRIMARY KEY (`tid`)
);
INSERT INTO `test`.`teacher` (`tid`, `tname`) VALUES ('10001', '李明');
INSERT INTO `test`.`teacher` (`tid`, `tname`) VALUES ('10002', '张丽');
二,新建Java Project项目mybatis1
1. 创建包结构如下
2.导入 mybatis jar包和mysql驱动包,mybatis jar包之前已经下载,mysql驱动包可在mysql安装目录下的lib文件夹找到
如图
3.在项目 src目录下创建XML 配置文件 命名为 mybatis-config.xml 此文件中作用是是配置数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式
内容如下
<?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>
<!-- 工作环境,默认是开发模式 工作模式有work -->
<environments default="development">
<!-- 配种工作环境为开发者模式,可配置多个environment连接多个数据库 如 mysql oracle sqlserver -->
<environment id="development">
<!-- 采用jdbc的事务管理 -->
<transactionManager type="JDBC" />
<!-- 配置数据源 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="a" />
</dataSource>
</environment>
</environments>
<!-- 注册sql映射文件 -->
<mappers>
<mapper resource="com/dao/StudentMapper.xml" />
<mapper resource="com/dao/TeacherMapper.xml" />
<mapper resource="com/dao/ClassesMapper.xml" />
</mappers>
</configuration>
注意:数据库密码需要改成你自己安装数据库时设置的密码
4.在com.pojo下创建每个表对应的实体类,并实现序列化接口,生成必要的方法,如参构造方法,无参构造方法,get,set方法,toString方法等
代码如下
package com.pojo;
import java.io.Serializable;
public class Classes implements Serializable {
private static final long serialVersionUID = -1817410267573286728L;
private Integer cid;
private String cname;
public Classes() {
super();
// TODO Auto-generated constructor stub
}
public Classes(Integer cid, String cname) {
super();
this.cid = cid;
this.cname = cname;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cid == null) ? 0 : cid.hashCode());
result = prime * result + ((cname == null) ? 0 : cname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Classes other = (Classes) obj;
if (cid == null) {
if (other.cid != null)
return false;
} else if (!cid.equals(other.cid))
return false;
if (cname == null) {
if (other.cname != null)
return false;
} else if (!cname.equals(other.cname))
return false;
return true;
}
@Override
public String toString() {
return "Classes [cid=" + cid + ", cname=" + cname + "]";
}
}
package com.pojo;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 6317146721573156174L;
private Integer sid;
private String sname;
private Integer age;
private String email;
private Integer tid;
private Integer cid;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student( String sname, Integer age, String email, Integer tid, Integer cid) {
super();
this.sname = sname;
this.age = age;
this.email = email;
this.tid = tid;
this.cid = cid;
}
public Student(Integer sid, String sname, Integer age, String email, Integer tid, Integer cid) {
super();
this.sid = sid;
this.sname = sname;
this.age = age;
this.email = email;
this.tid = tid;
this.cid = cid;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((cid == null) ? 0 : cid.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((sid == null) ? 0 : sid.hashCode());
result = prime * result + ((sname == null) ? 0 : sname.hashCode());
result = prime * result + ((tid == null) ? 0 : tid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (cid == null) {
if (other.cid != null)
return false;
} else if (!cid.equals(other.cid))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (sid == null) {
if (other.sid != null)
return false;
} else if (!sid.equals(other.sid))
return false;
if (sname == null) {
if (other.sname != null)
return false;
} else if (!sname.equals(other.sname))
return false;
if (tid == null) {
if (other.tid != null)
return false;
} else if (!tid.equals(other.tid))
return false;
return true;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", age=" + age + ", email=" + email + ", tid=" + tid
+ ", cid=" + cid + "]";
}
}
package com.pojo;
import java.io.Serializable;
public class Teacher implements Serializable {
private static final long serialVersionUID = -5672621111327057252L;
private Integer tid;
private String tname;
public Teacher() {
super();
// TODO Auto-generated constructor stub
}
public Teacher(Integer tid, String tname) {
super();
this.tid = tid;
this.tname = tname;
}
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((tid == null) ? 0 : tid.hashCode());
result = prime * result + ((tname == null) ? 0 : tname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Teacher other = (Teacher) obj;
if (tid == null) {
if (other.tid != null)
return false;
} else if (!tid.equals(other.tid))
return false;
if (tname == null) {
if (other.tname != null)
return false;
} else if (!tname.equals(other.tname))
return false;
return true;
}
@Override
public String toString() {
return "Teacher [tid=" + tid + ", tname=" + tname + "]";
}
}
5.在 com.dao下创建每个实体类对应的sq映射文件
代码如下
文件名 ClassesMapper.xml
<?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.dao.ClassesMappper">
<select id="selectClassesById" resultType="com.pojo.Classes">
select * from Classes where cid = #{cid}
</select>
<select id="selectClassesByAll" resultType="com.pojo.Classes">
select * from Classes
</select>
<insert id="insertClasses">
insert into Classes values(null,#{cname})
</insert>
<update id="updateClasses">
update Classes set cname = #{cname} where cid = #{cid}
</update>
<delete id="deleteClasses">
delete from Classes where cid = #{cid}
</delete>
</mapper>
文件名 StudentMapper.xml
<?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.dao.StudentMapper">
<select id="selectStudentById" resultType="com.pojo.Student">
select * from Student where sid = #{sid}
</select>
<select id="selectStudentByAll" resultType="com.pojo.Student">
select * from Student
</select>
<insert id="insertStudent">
insert into student values(null,#{sname},#{age},#{email},#{tid},#{cid})
</insert>
<update id="updateStudent">
update student set sname = #{sname},age =#{age} ,email =#{email} ,tid =#{tid} ,cid =#{cid} where sid = #{sid}
</update>
<delete id="deleteStudent">
delete from Student where sid = #{sid}
</delete>
</mapper>
文件名 TeacherMapper.xml
<?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.dao.TeacherMappper">
<select id="selectTeacherById" resultType="com.pojo.Teacher">
select * from Teacher where tid = #{tid}
</select>
<select id="selectTeacherByAll" resultType="com.pojo.Teacher">
select * from Teacher
</select>
<insert id="insertTeacher">
insert into Teacher values(null,#{tname})
</insert>
<update id="updateTeacher">
update Teacher set tname = #{tname} where tid = #{tid}
</update>
<delete id="deleteTeacher">
delete from Teacher where tid = #{tid}
</delete>
</mapper>
三,运行结果
创建一个测试类Demo 下面只演示对Student信息的增删查改操作,相关操作代码已做注释,读者可自行选择运行
package com.demo;
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.pojo.Student;
public class Demo {
public static void main(String[] args) {
// 创建SqlSessionFactory会话工厂
SqlSessionFactory factory = null;
try {
factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
//获取sqlSession与数据库交互的会话对象
SqlSession session = factory.openSession();
// // 查询一条数据
// Student student = session.selectOne("com.StudentMapper.selectStudentById", 100001);
// System.out.println(student);
// //查询所有数据
// List<Student> students = session.selectList("selectStudentByAll");
// System.out.println(students);
// //添加数据
// Student student = new Student("赵六",18,"111@qqq.com",1002,1002);
// int len = session.insert("insertStudent",student);
// if(len >0 ){
// System.out.println("添加学生信息成功...");
// }else{
// System.out.println("添加学生信息失败...");
// }
// //修改学生信息
// Student student = new Student("赵六",19,"222@qqq.com",1002,1002);
// student.setSid(100002);
// int len = session.insert("updateStudent",student);
// if(len >0 ){
// System.out.println("修改学生信息成功...");
// }else{
// System.out.println("修改学生信息失败...");
// }
// //删除学生信息
// int len = session.delete("deleteStudent",100002);
// if(len >0 ){
// System.out.println("修改学生信息成功...");
// }else{
// System.out.println("修改学生信息失败...");
// }
// 提交事务
session.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}