MyBatis 项目学习
一、项目目录结构
首先对整个项目目录做个大致了解。
①dao(Data Access Object)是数据访问对象,扮演MVC架构中的Model的角色,主要来封装访问数据的一些方法。
②domain,有人也叫做entity或者pojo,这个包下面封装了一些数据实体。
③mapping,这个包下面定义了数据库有关的映射文件(XML)。
④conf.xml,这个MyBatis的核心配置文件。定义了连接池(包括连接数据库必要的一些参数),映射文件路径。
⑤db.properties,这个里面就是把连接数据库的配置参数统一放在这里,要让这个文件配置生效,就要把这个文件导入到之前的conf.xml中。注意在项目移植的过程中,需要在这个文件下面更改一下配置参数。
二、设计流程
(1)首先,需要创建一个数据库mybatis并在这个数据库下面创建st_Student数据表。SQL语句如下:
-- 创建数据库,指定数据库默认编码 CREATE DATABASE `mybatis` DEFAULT CHARSET = utf8; USE `mybatis`; -- 创建学生表 CREATE TABLE st_Student ( StuID VARCHAR (12) PRIMARY KEY NOT NULL, StuName VARCHAR (8) NOT NULL, Sex VARCHAR (2) NOT NULL, BirthDate datetime NOT NULL, Native VARCHAR (40) NOT NULL, EntranceTime datetime NOT NULL, PoliticalFace VARCHAR (12) NOT NULL, Address VARCHAR (50) NOT NULL, PerPhone VARCHAR (11) NOT NULL, HPhone VARCHAR (11) NOT NULL, IDNum VARCHAR (18) NOT NULL, Photo VARCHAR (200) NOT NULL, ClassID VARCHAR (9) NOT NULL, DormitoryId VARCHAR (4) NOT NULL, National VARCHAR (2) NOT NULL, EmploymentStatus VARCHAR (10) NOT NULL ) DEFAULT CHARSET = utf8; -- 插入数据 INSERT INTO `mybatis`.`st_student` ( `StuID`, `StuName`, `Sex`, `BirthDate`, `Native`, `EntranceTime`, `PoliticalFace`, `Address`, `PerPhone`, `HPhone`, `IDNum`, `Photo`, `ClassID`, `DormitoryId`, `National`, `EmploymentStatus` ) VALUES ( '201412345678', '某某', '男', '1996-01-23', '中国湖南', '2014-09-01', '共青团员', '中国湖南', '12345678901', '01212345678', '43012219960901XXXX', '这是照片', '0001', '111', '汉', '无' );
(2) db.properties文件
(3)conf.xml配置文件
<?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> <properties resource="db.properties"></properties> <typeAliases> <typeAlias alias="Student" type="top.xiongxingwang.domain.Student" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="top/xiongxingwang/mapping/studentMapper.xml" /> </mappers> </configuration>
(4)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"> <!-- top.xiongxingwang.mapping.studentMapper --> <mapper namespace="top.xiongxingwang.dao.IStudentOperation"> <select id="getStuById" parameterType="String" resultType="Student"> select * from `st_student` where StuID=#{stuID}; </select> <select id="getAllStu" resultType="Student"> SELECT * FROM `st_student`; </select> <update id="updateById" parameterType="Student"> update `st_student` <set> <if test="stuName != null and stuName != '' "> st_student.StuName=#{stuName}, </if> <if test="sex != null and sex != '' "> st_student.Sex=#{sex}, </if> <if test="birthDate != null and birthDate != '' "> st_student.BirthDate=#{birthDate}, </if> <if test="Native != null and Native != '' "> st_student.Native=#{Native}, </if> <if test="entranceTime != null and entranceTime != '' "> st_student.EntranceTime=#{entranceTime}, </if> <if test="politicalFace != null and politicalFace != '' "> st_student.PoliticalFace=#{politicalFace}, </if> <if test="address != null and address != '' "> st_student.Address=#{address}, </if> <if test="perPhone != null and perPhone != '' "> st_student.PerPhone=#{perPhone}, </if> <if test="hPhone != null and hPhone != '' "> st_student.HPhone=#{hPhone}, </if> <if test="IDNum != null and IDNum != '' "> st_student.IDNum=#{IDNum}, </if> <if test="photo != null and photo != '' "> st_student.Photo=#{photo}, </if> <if test="classID != null and classID != '' "> st_student.ClassID=#{classID}, </if> <if test="dormitoryId != null and dormitoryId != '' "> st_student.DormitoryId=#{dormitoryId}, </if> <if test="national != null and national != '' "> st_student.National=#{national}, </if> <if test="employmentStatus != null and employmentStatus != '' "> st_student.EmploymentStatus=#{employmentStatus} </if> </set> where st_student.StuID=#{stuID}; </update> <insert id="insertOne" parameterType="Student"> INSERT INTO `st_student` ( `StuID`, `StuName`, `Sex`, `BirthDate`, `Native`, `EntranceTime`, `PoliticalFace`, `Address`, `PerPhone`, `HPhone`, `IDNum`, `Photo`, `ClassID`, `DormitoryId`, `National`, `EmploymentStatus` ) VALUES ( #{stuID}, #{stuName}, #{sex}, #{birthDate}, #{Native}, #{entranceTime}, #{politicalFace}, #{address}, #{perPhone}, #{hPhone}, #{IDNum}, #{photo}, #{classID}, #{dormitoryId}, #{national}, #{employmentStatus} ); </insert> <delete id="deleteById" parameterType="String"> DELETE FROM `st_student` WHERE StuID = #{stuID}; </delete> </mapper>
(5)IStudentOperation.java
package top.xiongxingwang.dao; import java.util.ArrayList; import top.xiongxingwang.domain.Student; public interface IStudentOperation { /** * 通过ID获取Student * * @param id * @return */ public Student getStuById(String id); /** * 获取所有的Student * * @return */ public ArrayList<Student> getAllStu(); /** * 根据ID更新学生信息 * * @param student */ public void updateById(Student student); /** * 插入一条学生记录 * * @param student */ public void insertOne(Student student); /** * 批量导入学生记录 * * @param student */ public void insertList(ArrayList<Student> student); /** * 根据ID删除学生记录 * * @param id */ public void deleteById(String stuId); }
(6)Student.java
package top.xiongxingwang.domain; import java.util.Date; public class Student { private String stuID; private String stuName; private String sex; private Date birthDate; private String Native; private Date entranceTime; private String politicalFace; private String address; private String perPhone; private String hPhone; private String IDNum; private String photo; private String classID; private String dormitoryId; private String national; private String employmentStatus; public Student() { } public Student(String stuID, String stuName, String sex, Date birthDate, String native1, Date entranceTime, String politicalFace, String address, String perPhone, String hPhone, String iDNum, String photo, String classID, String dormitoryId, String national, String employmentStatus) { super(); this.stuID = stuID; this.stuName = stuName; this.sex = sex; this.birthDate = birthDate; Native = native1; this.entranceTime = entranceTime; this.politicalFace = politicalFace; this.address = address; this.perPhone = perPhone; this.hPhone = hPhone; IDNum = iDNum; this.photo = photo; this.classID = classID; this.dormitoryId = dormitoryId; this.national = national; this.employmentStatus = employmentStatus; } public String getStuID() { return stuID; } public String getStuName() { return stuName; } public String getSex() { return sex; } public Date getBirthDate() { return birthDate; } public String getNative() { return Native; } public Date getEntranceTime() { return entranceTime; } public String getPoliticalFace() { return politicalFace; } public String getAddress() { return address; } public String getPerPhone() { return perPhone; } public String gethPhone() { return hPhone; } public String getIDNum() { return IDNum; } public String getPhoto() { return photo; } public String getClassID() { return classID; } public String getDormitoryId() { return dormitoryId; } public String getNational() { return national; } public String getEmploymentStatus() { return employmentStatus; } public void setStuID(String stuID) { this.stuID = stuID; } public void setStuName(String stuName) { this.stuName = stuName; } public void setSex(String sex) { this.sex = sex; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public void setNative(String Native) { this.Native = Native; } public void setEntranceTime(Date entranceTime) { this.entranceTime = entranceTime; } public void setPoliticalFace(String politicalFace) { this.politicalFace = politicalFace; } public void setAddress(String address) { this.address = address; } public void setPerPhone(String perPhone) { this.perPhone = perPhone; } public void sethPhone(String hPhone) { this.hPhone = hPhone; } public void setIDNum(String iDNum) { IDNum = iDNum; } public void setPhoto(String photo) { this.photo = photo; } public void setClassID(String classID) { this.classID = classID; } public void setDormitoryId(String dormitoryId) { this.dormitoryId = dormitoryId; } public void setNational(String national) { this.national = national; } public void setEmploymentStatus(String employmentStatus) { this.employmentStatus = employmentStatus; } @Override public String toString() { return "Student [stuID=" + stuID + ", stuName=" + stuName + ", sex=" + sex + ", birthDate=" + birthDate + ", Native=" + Native + ", entranceTime=" + entranceTime + ", politicalFace=" + politicalFace + ", address=" + address + ", perPhone=" + perPhone + ", hPhone=" + hPhone + ", IDNum=" + IDNum + ", photo=" + photo + ", classID=" + classID + ", dormitoryId=" + dormitoryId + ", national=" + national + ", employmentStatus=" + employmentStatus + "]"; } }
(7)MyBatisUtil.java
package top.xiongxingwang.main; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { private static String resource = "conf.xml"; private static SqlSessionFactory sqlSessionFactory = null; static { InputStream inputStream = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(true); } public static void sessionClose(SqlSession sqlSession) { sqlSession.close(); } }
(8)Main.java
新手请注意:对数据表如果有更改的话, 需要调用SQLSession的commit方法。
package top.xiongxingwang.main; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import org.apache.ibatis.session.SqlSession; import top.xiongxingwang.dao.IStudentOperation; import top.xiongxingwang.domain.Student; public class Main { static SimpleDateFormat dateFormater; static { dateFormater = new SimpleDateFormat("yyyy-MM-dd"); } public static void insertOneTest() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IStudentOperation stuOper = sqlSession.getMapper(IStudentOperation.class); Student student = null; try { student = new Student("123456", "张三", "男", dateFormater.parse("1995-01-05"), "中国广东", dateFormater.parse("1995-01-05"), "共青团员", "中国广东深圳", "13812345678", "012-1234567", "43012219960123XXXX", "这是照片", "0001", "123", "汉", "无"); stuOper.insertOne(student); sqlSession.commit(); System.out.println("成功插入一条记录!"); } catch (ParseException e) { e.printStackTrace(); } finally { sqlSession.close(); } } public static void printAllStuTest() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IStudentOperation stuOper = sqlSession.getMapper(IStudentOperation.class); ArrayList<Student> stuList = stuOper.getAllStu(); System.out.println("数据表中所有的记录如下:"); for (Student stu : stuList) { System.out.println(stu); } sqlSession.close(); } public static void deleteByIdTest() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IStudentOperation stuOper = sqlSession.getMapper(IStudentOperation.class); String stuId = "123456"; stuOper.deleteById(stuId); sqlSession.commit(); System.out.println("成功删除一行记录!"); sqlSession.close(); } // 以更新学号为123456的学生信息为例 public static void updateByIdTest() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IStudentOperation stuOper = sqlSession.getMapper(IStudentOperation.class); // 首先获取123456学生的原来的信息 Student student = stuOper.getStuById("123456"); student.setStuName("李四"); student.setAddress("美国"); stuOper.updateById(student); sqlSession.commit(); System.out.println("成功更新一行记录!"); sqlSession.close(); } public static void main(String[] args) { // 打印数据表中的所有记录 printAllStuTest(); // 打印分隔符 System.out.println("----------SEPARATOR----------"); // 插入记录 insertOneTest(); // 打印插入一条记录之后的数据表中的所有记录 printAllStuTest(); // 打印分隔符 System.out.println("----------SEPARATOR----------"); // 更新记录 updateByIdTest(); // 打印更新一条记录之后的数据表中的所有记录 printAllStuTest(); // 打印分隔符 System.out.println("----------SEPARATOR----------"); // 删除记录 deleteByIdTest(); // 打印删除一条记录之后的数据表中的所有记录 printAllStuTest(); // 打印分隔符 System.out.println("----------SEPARATOR----------"); } }
三、参考链接
① 项目文件下载链接;
④ MyBatis学习总结;
时间: 2024-10-17 11:50:18