1.项目结构
2. 主配置文件 mybatis-config.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="config/jdbc.properties" />
<!--延迟加载配置setting-->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<!-- <typeAlias type="com.zhq.entity" alias="Grade" /> -->
<package name="com.zhq.entity"/>
</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>
<!-- mapping 文件路径配置 -->
<mappers>
<!-- <mapper resource="com/etc/mappers/UserMapper.xml" /> -->
<package name="com.zhq.dao"/>
</mappers>
</configuration>
3. 数据库配置文件 jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/myschool?characterEncoding\=utf-8
username=root
password=root
4. 日志配置文件 log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.zhq.dao=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
5. 接口配置文件(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.zhq.dao.GradeDao">
<!--配置 实体类属性和数据列的关联,如果不配置默认同名传递,匹配不到的则为空-->
<resultMap type="Grade" id="g">
<id column="gradeId" property="gradeId"/>
<result column="gradeName" property="gradeName"/>
<!--一对多 -->
<collection property="students" column="gradeId" select="com.zhq.dao.StudentDao.findByGradeId"></collection>
</resultMap>
<select id="find" resultType="Grade">
select * from grade
</select>
<select id="findById" resultMap="g" parameterType="int">
select * from grade where gradeId=#{Id}
</select>
<insert id="add" parameterType="Grade" useGeneratedKeys="true" keyProperty="gradeId" >
insert into grade value(null,#{gradeName})
</insert>
<update id="update" parameterType="Grade">
update grade set gradeName=#{gradeName} where gradeId=#{gradeId}
</update>
<delete id="delete" parameterType="int">
delete from grade where gradeId=#{id}
</delete>
</mapper>
<?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.zhq.dao.StudentDao">
<!--二级缓存配置cache-->
<!-- <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"></cache> -->
<resultMap type="Student" id="studentList">
<id property="studentNo" column="studentNo"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<result property="phone" column="phone"/>
<result property="address" column="address"/>
<result property="email" column="email"/>
<result property="birthday" column="birthday"/>
<!--多对一 -->
<association property="grade" column="gradeId" select="com.zhq.dao.GradeDao.findById"></association>
</resultMap>
<select id="find" resultMap="studentList">
select * from student
</select>
<select id="find_1" resultMap="studentList" parameterType="Map">
select * from student limit #{offset},#{limit}
</select>
<select id="findByGradeId" resultType="Student" parameterType="int">
select * from student where gradeId=#{gradeId}
</select>
<select id="findStudentBySex" resultType="Student" parameterType="Map" statementType="CALLABLE">
{call p_findStudentBySex(#{sex})}
</select>
<select id="getStudentCount" parameterType="Map" statementType="CALLABLE">
{call p_getStudentCount(#{count,mode=OUT,jdbcType=INTEGER})}
</select>
<select id="search" parameterType="Map" resultMap="studentList">
select * from student
<where>
<if test="name != null">
name like #{name}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
<if test="age != 0">
and age = #{age}
</if>
</where>
</select>
<select id="searchStudentByManyName" resultMap="studentList">
select * from student where name in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
</mapper>
6. 接口配置(注解方式)
package com.zhq.dao;
import java.util.List;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import com.zhq.entity.Admin;
public interface AdminDao {
@Select("select * from admin")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="loginId",property="loginId"),
@Result(column="loginPwd",property="loginPwd"),
@Result(column="isAdmin",property="isAdmin")
})
public List<Admin> findAllAdmin();
}
package com.zhq.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.zhq.entity.Subject;
public interface SubjectDao {
//查找所有课程
@Select("select * from subject")
@Results({
@Result(id=true,column="subjectNo",property="subjectNo"),
@Result(column="subjectName",property="subjectName"),
@Result(column="classHour",property="classHour"),
@Result(column="gradeId",property="grade",one=@One(select="com.zhq.dao.GradeDao.findById"))
})
public List<Subject> findAllSubjects();
//添加新课程
@Insert("insert into subject value(null,#{subjectName},#{classHour},#{grade.gradeId})")
public int add(Subject subject);
//通过ID修改课程
@Update("update subject set subjectName=#{subjectName},classHour=#{classHour},gradeId=#{grade.gradeId} where subjectNo=#{subjectNo}")
public int update(Subject subject);
//删除课程信息
@Delete("delete from subject where subjectNo=#{id}")
public int delete(int id);
}
7. 实体类
package com.zhq.entity;
public class Admin {
private int id;
private String loginId;
private String loginPwd;
private String isAdmin;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public String getLoginPwd() {
return loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
public String getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(String isAdmin) {
this.isAdmin = isAdmin;
}
@Override
public String toString() {
return "Admin [id=" + id + ", loginId=" + loginId + ", loginPwd=" + loginPwd + ", isAdmin=" + isAdmin + "]";
}
}
package com.zhq.entity;
import java.util.List;
public class Grade {
private int gradeId;
private String gradeName;
private List<Student> students=null;
public int getGradeId() {
return gradeId;
}
public void setGradeId(int gradeId) {
this.gradeId = gradeId;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Grade [gradeId=" + gradeId + ", gradeName=" + gradeName + "]";
}
}
package com.zhq.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Student {
private int studentNo;
private String name;
private String sex;
private int age;
private String phone;
private String address;
private Date birthday;
private String email;
private Grade grade;
public int getStudentNo() {
return studentNo;
}
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public String toString() {
return "Student [studentNo=" + studentNo + ", name=" + name + ", sex=" + sex + ", age=" + age + ", phone="
+ phone + ", address=" + address + ", birthday=" + sdf.format(birthday) + ", email=" + email
+ "]";
}
}
package com.zhq.entity;
public class Subject {
private int subjectNo;
private String subjectName;
private int classHour;
private Grade grade;
public int getSubjectNo() {
return subjectNo;
}
public void setSubjectNo(int subjectNo) {
this.subjectNo = subjectNo;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public int getClassHour() {
return classHour;
}
public void setClassHour(int classHour) {
this.classHour = classHour;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Subject [subjectNo=" + subjectNo + ", subjectName=" + subjectName + ", classHour=" + classHour
+ "]";
}
}
8. Dao
package com.zhq.dao;
import java.util.List;
import com.zhq.entity.Grade;
public interface GradeDao {
//查找所有年级信息
public List<Grade> find();
//添加新年级
public int add(Grade grade);
//修改年级信息
public int update(Grade grade);
//删除年级信息
public int delete(int id);
//通过年级编号查找年级信息
public Grade findById(int id);
}
package com.zhq.dao;
import java.util.List;
import java.util.Map;
import com.zhq.entity.Student;
public interface StudentDao {
//查找所有学生信息分页方式一
public List<Student> find();
//查找所有学生信息分页方式二
public List<Student> find_1(Map<String,Integer> map);
//通过年级查学生
public List<Student> findByGradeId(int id);
//通过性别查学生
public List<Student> findStudentBySex(Map<String,String> map);
//查找全校学生总数
public void getStudentCount(Map<String,Integer> map);
//多条件查询
public List<Student> search(Map<Object,Object> map);
//模糊查询不同名字的学生
public List<Student> searchStudentByManyName(List<String> namelist);
}
9. Service
package com.zhq.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import com.zhq.dao.StudentDao;
import com.zhq.entity.Student;
import com.zhq.utils.SQLSessionFactory;
public class StudentService {
//分页方法一:查找学生offset(开始下标),limit(查询行数)
public List<Student> find(int offset,int limit){
//读取主配置文件,把主配置文件进行XML解析,解析成输入流
SqlSession sqlSession = SQLSessionFactory.getSession();
/*List<Grade> list = sqlSession.selectList("find");*/
/*StudentDao dao=sqlSession.getMapper(StudentDao.class);*/
RowBounds rb=new RowBounds(offset, limit);
List<Student> list = sqlSession.selectList("com.zhq.dao.StudentDao.find", null, rb) ;
sqlSession.close(); //关闭连接对象
return list;
}
//分页方法二:查找学生offset(开始下标),limit(查询行数)
public List<Student> find_1(int offset,int limit){
//读取主配置文件,把主配置文件进行XML解析,解析成输入流
SqlSession sqlSession = SQLSessionFactory.getSession();
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("offset", offset);
map.put("limit", limit);
StudentDao dao=sqlSession.getMapper(StudentDao.class);
List<Student> list=dao.find_1(map);
sqlSession.close(); //关闭连接对象
return list;
}
//通过性别查找学生
public List<Student> findStudentBySex(String sex){
//读取主配置文件,把主配置文件进行XML解析,解析成输入流
SqlSession sqlSession = SQLSessionFactory.getSession();
Map<String,String> map=new HashMap<String,String>();
map.put("sex", sex);
StudentDao dao=sqlSession.getMapper(StudentDao.class);
List<Student> list=dao.findStudentBySex(map);
sqlSession.close(); //关闭连接对象
return list;
}
//获取学生总人数
public int getStudentCount() {
SqlSession sqlSession = SQLSessionFactory.getSession();
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("count", 0);
StudentDao dao=sqlSession.getMapper(StudentDao.class);
dao.getStudentCount(map);
sqlSession.close(); //关闭连接对象
return map.get("count");
}
//多条件动态查询
public List<Student> search(String name,String sex,int age){
//读取主配置文件,把主配置文件进行XML解析,解析成输入流
SqlSession sqlSession = SQLSessionFactory.getSession();
Map<Object,Object> map=new HashMap<Object,Object>();
map.put("name", name);
map.put("sex", sex);
map.put("age", age);
StudentDao dao=sqlSession.getMapper(StudentDao.class);
List<Student> list=dao.search(map);
sqlSession.close(); //关闭连接对象
return list;
}
//模糊查询不同名字的学生
public List<Student> searchStudentByManyName(List<String> namelist){
SqlSession sqlSession = SQLSessionFactory.getSession();
StudentDao dao=sqlSession.getMapper(StudentDao.class);
List<Student> list=dao.searchStudentByManyName(namelist);
return list;
}
}
package com.zhq.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.zhq.dao.GradeDao;
import com.zhq.entity.Grade;
import com.zhq.utils.SQLSessionFactory;
public class GradeService {
public List<Grade> find(){
//读取主配置文件,把主配置文件进行XML解析,解析成输入流
SqlSession sqlSession = SQLSessionFactory.getSession();
/*List<Grade> list = sqlSession.selectList("find");*/
GradeDao dao=sqlSession.getMapper(GradeDao.class);
List<Grade> list = dao.find() ;
sqlSession.close(); //关闭连接对象
return list;
}
public int add(Grade grade) {
SqlSession sqlSession=SQLSessionFactory.getSession();
GradeDao dao=sqlSession.getMapper(GradeDao.class);
int result=dao.add(grade);
sqlSession.commit();
sqlSession.close();
return result;
}
public int update(Grade grade) {
SqlSession sqlSession=SQLSessionFactory.getSession();
GradeDao dao=sqlSession.getMapper(GradeDao.class);
int result=dao.update(grade);
sqlSession.commit();
sqlSession.close();
return result;
}
public int delete(int id) {
SqlSession sqlSession=SQLSessionFactory.getSession();
GradeDao dao=sqlSession.getMapper(GradeDao.class);
int result=dao.delete(id);
sqlSession.commit();
sqlSession.close();
return result;
}
public Grade findById(int id) {
SqlSession sqlSession=SQLSessionFactory.getSession();
GradeDao dao=sqlSession.getMapper(GradeDao.class);
Grade result=dao.findById(id);
sqlSession.close();
return result;
}
}
package com.zhq.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.zhq.dao.AdminDao;
import com.zhq.entity.Admin;
import com.zhq.utils.SQLSessionFactory;
public class AdminService {
public List<Admin> findAllAdmin(){
SqlSession sqlSession = SQLSessionFactory.getSession();
/*List<Grade> list = sqlSession.selectList("find");*/
AdminDao dao=sqlSession.getMapper(AdminDao.class);
List<Admin> list = dao.findAllAdmin();
sqlSession.close(); //关闭连接对象
return list;
}
}
package com.zhq.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.zhq.dao.SubjectDao;
import com.zhq.entity.Subject;
import com.zhq.utils.SQLSessionFactory;
public class SubjectService {
//查询所有课程
public List<Subject> findAllSubjects(){
SqlSession sqlSession = SQLSessionFactory.getSession();
SubjectDao dao=sqlSession.getMapper(SubjectDao.class);
List<Subject> list = dao.findAllSubjects();
sqlSession.close(); //关闭连接对象
return list;
}
//添加新课程
public int add(Subject subject) {
SqlSession sqlSession=SQLSessionFactory.getSession();
SubjectDao dao=sqlSession.getMapper(SubjectDao.class);
int result=dao.add(subject);
sqlSession.commit();
sqlSession.close();
return result;
}
//修改课程
public int update(Subject subject) {
SqlSession sqlSession=SQLSessionFactory.getSession();
SubjectDao dao=sqlSession.getMapper(SubjectDao.class);
int result=dao.update(subject);
sqlSession.commit();
sqlSession.close();
return result;
}
//删除某个课程信息
public int delete(int id) {
SqlSession sqlSession=SQLSessionFactory.getSession();
SubjectDao dao=sqlSession.getMapper(SubjectDao.class);
int result=dao.delete(id);
sqlSession.commit();
sqlSession.close();
return result;
}
}
10. Utils
package com.zhq.utils;
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;
public class SQLSessionFactory {
static Reader reader = null;
static SqlSessionFactory sqlSessionFactory=null;
private SQLSessionFactory() {}
//这是一个静态语句块,用于读取主配置文件,因为主配置文件只需要读取一次。
static {
try {
//形成输入流
reader = Resources.getResourceAsReader("config/mybatis-config.xml");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
//SqlSession工厂,只需要一个,所以做成单例模式
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory == null){
synchronized (SQLSessionFactory.class) {
if(sqlSessionFactory == null){
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
}
}
return sqlSessionFactory;
}
public static SqlSession getSession(){
//返回一个数据操作连接对象
return getSqlSessionFactory().openSession();
}
}
11. Test
package com.zhq.controller;
import java.util.List;
import com.zhq.entity.Admin;
import com.zhq.service.AdminService;
public class AdminTest {
public static void main(String[] args) {
AdminService ser=new AdminService();
List<Admin>list=ser.findAllAdmin();
for(Admin admin:list) {
System.out.println(admin);
}
}
}
package com.zhq.controller;
import java.util.List;
import javax.swing.text.AbstractDocument.Content;
import com.zhq.entity.Grade;
import com.zhq.entity.Student;
import com.zhq.service.GradeService;
public class GradeTest {
public static void main(String[] args) {
GradeService ser=new GradeService();
//查找所有年级
/*List<Grade>list=ser.find();
for(Grade grade:list) {
System.out.println(grade);
}*/
//通过ID查年级学生
Grade g=ser.findById(3);
if(g!=null) {
System.out.println(g);
if(g.getStudents()!=null) {
for(Student student:g.getStudents()) {
System.out.println(student);
}
}
}
/*//添加新年级
Grade grade=new Grade();
grade.setGradeName("9年级");
if(ser.add(grade)>0) {
System.out.println("添加成功!");
System.out.println("添加新的ID:"+grade.getGradeId());
}else {
System.out.println("添加失败!");
}*/
//修改年级
/*GradeService ser=new GradeService();
Grade grade=new Grade();
grade.setGradeName("十年级");
grade.setGradeId(19);
if(ser.update(grade)>0) {
System.out.println("修改成功!");
}else {
System.out.println("修改失败!");
}*/
//删除年级
/*GradeService ser=new GradeService();
if(ser.delete(19)>0) {
System.out.println("删除成功!");
}else {
System.out.println("删除失败!");
}*/
}
}
package com.zhq.controller;
import java.util.ArrayList;
import java.util.List;
import com.zhq.entity.Student;
import com.zhq.service.StudentService;
public class StudentTest {
public static void main(String[] args) {
StudentService ser= new StudentService();
//分页查找学生
/*System.out.println("分页方式一:");//适用数据量不大的情况
for(Student student:ser.find(5,5)) {
System.out.println(student);
}
System.out.println("分页方式二:");//适用数据量大的情况
for(Student student:ser.find_1(5,5)) {
System.out.println(student);
}*/
//按性别查找学生
/*for(Student student:ser.findStudentBySex("女")) {
System.out.println(student);
}*/
/*System.out.println("全校总人数:"+ser.getStudentCount());*/
//动态SQL多条件查询
/*for(Student student:ser.search("%李%","男",0)) {
System.out.println(student);
}*/
//动态SQL模糊查询不同名字的学生
List<String> namelist=new ArrayList<String>();
namelist.add("李小军");
namelist.add("李相赫");
namelist.add("刘巧妹");
namelist.add("李艳红");
for(Student student:ser.searchStudentByManyName(namelist)) {
System.out.println(student);
}
}
}
package com.zhq.controller;
import com.zhq.entity.Grade;
import com.zhq.entity.Subject;
import com.zhq.service.SubjectService;
public class SubjectTest {
public static void main(String[] args) {
SubjectService ser=new SubjectService();
//添加新课程
Subject sub1=new Subject();
Grade grade=new Grade();
grade.setGradeId(4);
sub1.setSubjectName("MySpring");
sub1.setClassHour(80);
sub1.setGrade(grade);
/*if(ser.add(sub1)>0) {
System.out.println("添加成功!");
}else {
System.out.println("添加失败!");
}*/
//修改课程
/*sub1.setSubjectNo(14);
sub1.setClassHour(100);
if(ser.update(sub1)>0) {
System.out.println("修改成功!");
}else {
System.out.println("修改失败!");
}*/
/*if(ser.delete(15)>0) {
System.out.println("删除成功!");
}else {
System.out.println("删除失败!");
}*/
//查询所有课程
for(Subject sub:ser.findAllSubjects()) {
System.out.println(sub.getGrade().getGradeName()+sub);
}
}
}