一、mybatis 所需相关jar 文件:
二、项目包结构
<!-- Mybatis 主配置文件 -->
<?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>
<!-- 给实体类起别名 可以方便在mapper文件 使用 -->
<typeAliases>
<typeAlias type="mybatis.entity.Student" alias="stu" />
<typeAlias type="mybatis.entity.Grade" alias="grade" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<!-- Oracle数据库驱动 -->
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<!-- Oracle数据库URL -->
<property name="url" value="jdbc:oracle:thin:@localhost:1521:qxgora" />
<!-- 数据库用户名 -->
<property name="username" value="xiaoqiu" />
<!-- 数据库密码 -->
<property name="password" value="xiaoqiu" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射Mapper.xml 有几个就映射几个 mapper -->
<mapper resource="mybatis/entity/StudentMapper.xml" />
</mappers>
</configuration>
//Mybatis 操作session 工具类
package mybatis.util;
import java.io.IOException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public final class MybatisUtil {
//2.获得Session (sqlSession)
//3.调用Mapper.xml
//4.返回结果
//session工厂
private static SqlSessionFactory factory = null;
//session
private static SqlSession session = null;
//获取当前项目下 mybatis 主配置文件
private static String resouces = "mybatis-config.xml";
/**
* 获得session
* @return
* @throws IOException
*/
public static SqlSession getSqlSession() throws IOException {
factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resouces));
if (null == session) {
session = factory.openSession();
}
return session;
}
/**
* 关闭session
*/
public static void closeSession(){
session.close();
}
}
//实体类对象 student
package mybatis.entity;
import java.util.Date;
public class Student {
private int stuId;
private String stuName;
private int stuAge;
private Date stuBirthDay;
private String stuPwd;
private int stuGid;
//外键()
private Grade grade;
public int getStuGid() {
return stuGid;
}
public void setStuGid(int stuGid) {
this.stuGid = stuGid;
}
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
public Date getStuBirthDay() {
return stuBirthDay;
}
public void setStuBirthDay(Date stuBirthDay) {
this.stuBirthDay = stuBirthDay;
}
public String getStuPwd() {
return stuPwd;
}
public void setStuPwd(String stuPwd) {
this.stuPwd = stuPwd;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student [学生编号=" + stuId + ", 学生姓名=" + stuName + ", 年龄="
+ stuAge + ", 出生日期=" + stuBirthDay + ", 密码="
+ stuPwd + ", 年级=" + grade.getgName() + "]";
}
}
//实体对象类 grade
package mybatis.entity;
public class Grade {
private int gId;
private String gName;
public int getgId() {
return gId;
}
public void setgId(int gId) {
this.gId = gId;
}
public String getgName() {
return gName;
}
public void setgName(String gName) {
this.gName = gName;
}
}
//学生信息 DAO 接口类
package mybatis.dao;
import java.util.List;
import mybatis.entity.Student;
public interface IStudentDao {
/**
* 按学生姓名姓氏模糊查询学生信息
* @param stuName 姓氏
* @return 学生集合
*/
public abstract List<Student> selectStudentByLike(String stuName);
/**
* 查询所有学生信息
* @return
*/
public abstract List<Student> selectStudents();
/**
* 新增学生信息
* @param stu 学生对象
* @return 受影响的行数
*/
public abstract int insertStudent(Student stu);
/**
* 修改学生信息
* @param stu 学生对象
* @return 受影响的行数
*/
public abstract int updateStudent(Student stu);
/**
* 按主键学生信息
* @param stuId 主键(学生Id)
* @return 受影响的行数
*/
public abstract int deleteStudent(int stuId);
}
<?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="mybatis.dao.IStudentDao">
<!-- 返回结果的Map 唯一的 通过id属性来找 -->
<resultMap type="mybatis.entity.Student" id="stuMap">
<!-- 一般没什么特殊情况 只需要写property属性即可 column 属性只是为了和数据库一致 -->
<result property="stuId" column="STUID" />
<result property="stuName" column="STUNAME" />
<result property="stuAge" column="STUAGE" />
<result property="stuBirthDay" column="STUBIRTHDAY" />
<result property="stuPwd" column="STUPWD" />
<!-- 外键属性 -->
<association property="grade" javaType="mybatis.entity.Grade"
column="STUGID">
<result property="gId" column="GID" />
<result property="gName" column="GNAME" />
</association>
</resultMap>
<!-- 替代,语句中的内容,简写 -->
<sql id="stus">
stuId,stuName,stuAge,stuBirthDay,stuPwd,stuGid
</sql>
<select id="selectStudentByLike" resultMap="stuMap" parameterType="java.lang.String">
select *
from
student s
INNER JOIN GRADE g ON g.gId= s.stugId
WHERE stuName LIKE #{stuName}
</select>
<!-- 查询所有学生信息 resultType 代表当前结果返回什么 如果是List<Student>
则直接返回当前实体类即可 不提供返回集合
resultMap 代表当前结果所对应的Map -->
<select id="selectStudents" resultType="stu" resultMap="stuMap">
select *
from
student s
INNER JOIN GRADE g ON g.gId= s.stugId
</select>
<!-- 新增学生信息 parameterType 代表的当前方法参数 什么类型的 insert 没有返回属性 -->
<insert id="insertStudent" parameterType="stu">
<!-- 在执行之前获取序列 以便于插入主键值 -->
<selectKey resultType="int" order="BEFORE" keyProperty="stuId">
<![CDATA[
select seq_student.nextval from dual
]]>
</selectKey>
<![CDATA[
insert into student
values(#{stuId},#{stuName},#{stuAge},#{stuBirthDay},#{stuPwd},#{stuGid})
]]>
</insert>
<!-- 更新学生信息 -->
<update id="updateStudent" parameterType="stu">
<![CDATA[
update student
set
stuName = #{stuName},
stuAge = #{stuAge},
stuBirthDay = #{stuBirthDay},
stuPwd = #{stuPwd},
stuGid = #{stuGid}
where stuId = #{stuId}
]]>
</update>
<!-- 按ID(主键值 ) 删除学生信息 -->
<delete id="deleteStudent" parameterType="int">
<![CDATA[
delete
from student
where
stuId = #{stuId}
]]>
</delete>
</mapper>
//操作学生信息 接口实现操作类
package mybatis.dao.impl;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import mybatis.dao.IStudentDao;
import mybatis.entity.Grade;
import mybatis.entity.Student;
import mybatis.util.MybatisUtil;
@SuppressWarnings("unused")
public class StudentDaoImpl implements IStudentDao {
/**
* 查询所有学生信息
*/
@Override
public List<Student> selectStudents() {
try {
SqlSession session = MybatisUtil.getSqlSession();
return session.selectList("mybatis.dao.IStudentDao.selectStudents");
//return session.getMapper(IStudentDao.class).selectStudents();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
/**
* 新增学生信息
*/
@Override
public int insertStudent(Student stu) {
int res = -1;
SqlSession session = null;
try {
session = MybatisUtil.getSqlSession();
res = session.getMapper(IStudentDao.class).insertStudent(stu);
session.commit();
} catch (Exception e) {
session.rollback();
} finally {
MybatisUtil.closeSession();
}
return res;
}
/**
* 更新学生信息
*/
@Override
public int updateStudent(Student stu) {
int res = -1;
SqlSession session = null;
try {
session = MybatisUtil.getSqlSession();
res = session.getMapper(IStudentDao.class).updateStudent(stu);
session.commit();
} catch (Exception e) {
session.rollback();
} finally {
MybatisUtil.closeSession();
}
return res;
}
/**
* 删除学生信息
* @param stuId
* @return
*/
@Override
public int deleteStudent(int stuId) {
int res = -1;
SqlSession session = null;
try {
session = MybatisUtil.getSqlSession();
res = session.getMapper(IStudentDao.class).deleteStudent(stuId);
session.commit();
} catch (Exception e) {
}
return res;
}
@Override
public List<Student> selectStudentByLike(String stuName) {
try {
SqlSession session = MybatisUtil.getSqlSession();
return session.selectList("mybatis.dao.IStudentDao.selectStudentByLike",stuName+"%");
// return session.getMapper(IStudentDao.class).selectStudentByLike("%"+stuName+"%");
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
//数据测试类
package mybatis.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import mybatis.dao.IStudentDao;
import mybatis.dao.impl.StudentDaoImpl;
import mybatis.entity.Student;
public class MyBatisTest {
//引用DAO 接口
private static IStudentDao stuDao = new StudentDaoImpl();
public static IStudentDao getStuDao() {
return stuDao;
}
public static void setStuDao(IStudentDao stuDao) {
MyBatisTest.stuDao = stuDao;
}
/**
* 测试方法
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
selectStuByLike();
// 查询所有
//selectStus();
// 新增
// insertStu();
// 修改
// updateStu();
// 删除
//deleteStu();
}
//按姓氏查询学生信息
private static void selectStuByLike() {
String stuName ="张";
for (Student stu : stuDao.selectStudentByLike(stuName)) {
System.out.println(stu);
}
}
//查询所有学生信息
private static void selectStus() {
for (Student s : stuDao.selectStudents()) {
System.out.println(s);
}
}
//删除学生信息
private static void deleteStu() {
int stuId = 0;
int res = stuDao.deleteStudent(stuId);
if (res > 0) {
System.out.println("OK");
} else {
System.out.println("NO");
}
}
//更新学生信息
private static void updateStu() throws ParseException {
Student stu = new Student();
stu.setStuName("你好");
stu.setStuAge(25);
stu.setStuPwd("456789");
stu.setStuBirthDay(new SimpleDateFormat("yyyy-MM-dd").parse("2010-09-09"));
stu.setStuGid(3);
stu.setStuId(24);
int res = new StudentDaoImpl().updateStudent(stu);
if (res > 0) {
System.out.println("OK");
} else {
System.out.println("NO");
}
}
//新增学生信息
private static void insertStu() throws ParseException {
Student stu = new Student();
stu.setStuName("hhh");
stu.setStuAge(20);
stu.setStuPwd("12345");
stu.setStuBirthDay(new SimpleDateFormat("yyyy-MM-dd").parse("2012-09-09"));
stu.setStuGid(3);
int res = new StudentDaoImpl().insertStudent(stu);
if (res > 0) {
System.out.println("OK");
} else {
System.out.println("NO");
}
}
}