Mybatis配置使用

1.引入所需要的maven依赖:

        <!-- Junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>


        <!-- 数据库连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!--日志依赖包-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
        </dependency>

2.新建db.properties(一般在resoures目录)文件,配置数据库信息

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/yh01_ssm_mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
db.username=root
db.password=123456

3.新建日志配置文件log4j.properties(一般在resoures目录)

###
log4j.rootLogger=debug,stdout,logfile
#####
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
##
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=src/main/resources/logs/zr.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}%l%F%p%m%n

4.编写实体类Student(在com.po包下):

public class Student {

    private Integer id;
    private String username;
    private String password;
    private Integer clazznumber;
    private String clazzname;
    private int sex;
    private String address;
    private String email;
    private String phone;
    private int flag;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getClazznumber() {
        return clazznumber;
    }
    public void setClazznumber(Integer clazznumber) {
        this.clazznumber = clazznumber;
    }
    public String getClazzname() {
        return clazzname;
    }
    public void setClazzname(String clazzname) {
        this.clazzname = clazzname;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    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 String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public int getFlag() {
        return flag;
    }
    public void setFlag(int flag) {
        this.flag = flag;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", username=" + username + ", password=" + password + ", clazznumber="
                + clazznumber + ", clazzname=" + clazzname + ", sex=" + sex + ", address=" + address + ", email="
                + email + ", phone=" + phone + ", flag=" + flag + "]";
    }
}

5.编写dao层代码StuDao(在com.dao包下):

package com.dao;

import java.util.List;
import com.po.Student;
public interface StuDao {

public Student FindStu(Integer id);

public List<Student> FindStus();

public void InsertStu(Student stu);

public void DeleteStu(Integer id);

//完全按照传过来的数据进行更新
public void UpdateStu(Student stu);

}

6.编写Mapper配置文件StuMapper.xml(一般放在resources/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.dao.StuDao">
<!--
当前配置下开启二级缓存
LRU.最近最少使用策略,移除最长时间不被使用的对象
FIFO.先进先出策略,按对象进入缓存的顺序来移除他们
SOFT.软引用策略,移除基于垃圾回收器状态和软引用规则的对象
WEAK.弱引用策略,更积极地移除基于垃圾收集器状态和弱引用规则的对象
创建一个LRU缓存,每隔60秒刷新,最大储存512个对象,而且返回的对象被认为是只读的
-->
<cache eviction="LRU" flushInterval="6000" size="512" readOnly="true" />

<select id="FindStu" parameterType="int" resultType="Student">
select * from student where id = #{id}
</select>
<!-- 查询集合 -->
<resultMap type="Student" id="Stus">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="clazznumber" property="clazznumber"/>
<result column="clazzname" property="clazzname"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<result column="phone" property="phone"/>
<result column="email" property="email"/>
<result column="flag" property="flag"/>
</resultMap>
<select id="FindStus" resultMap="Stus">
select id,username,password,clazznumber,clazzname,sex,address,email,phone,flag from student
</select>
<!-- 插入单个用户 -->
<insert id="InsertStu" parameterType="Student">
insert into student(username,password,clazznumber,clazzname,sex,address,phone,email) values(
#{username},#{password},#{clazznumber},#{clazzname},#{sex},#{address},#{phone},#{email})
</insert>
<!-- 删除单个用户 -->
<delete id="DeleteStu" parameterType="int">
delete from student where id=#{id}
</delete>
<!-- 更新单个用户 -->
<update id="UpdateStu" parameterType="Student">
update student set username=#{username},
password=#{password},clazznumber=#{clazznumber},
clazzname=#{clazzname},sex=#{sex},
address=#{address}, email=#{email},
phone=#{phone} ,flag=#{flag}
where id=#{id}
</update>
</mapper>
 

7.新建mybatis的SqlMapConfig.xml配置类(一般在resoures目录)。

<?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>
    
    <!-- 1.定义别名 减少数据库冗余-->
    <typeAliases>
        <!-- 方法1 -->
        <typeAlias type="com.po.Student" alias="Student"/>
    
        <!-- 方法2 写入包名,它会自动搜索需要的Java Bean -->
        <!-- <package name="com.po"/> -->
    </typeAliases>
    <!-- 定义数据源 -->
     <environments default="development">
         <environment id="development">
             <!-- 事务管理,type=JDBC指使用了JDBC的提交和回滚设置;type=MANAGED指让容器实现对事务的管理-->
             <transactionManager type="JDBC"/>    
             <dataSource type="POOLED">
                 <property name="driver"     value="${db.driver}"/>
                 <property name="url"         value="${db.url}"/>
                 <property name="username"     value="${db.username}"/>
                 <property name="password"     value="${db.password}"/>
             </dataSource>
         </environment>
     </environments>
     <mappers>
         <mapper resource="mapper/StuMapper.xml"/>
     
         <!-- <package name="com.dao"/> -->
     </mappers>
</configuration>

8.新建MybatisUntil工具类(com.util包下):

public class MybatisUntil {
    
    public static SqlSession openSession() throws IOException{
        String resource = "SqlMapConfig.xml";
        //1.读取Mybatis配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 2、根据配置文件创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return  sqlSessionFactory.openSession();
    } 
}

9.调用mybatis工具类进行测试(test.StuTest):


public class StuTest {

/*session.commit(); 提交事务
* 更新,删除,插入都需要提交事务
*/

//查询单个用户信息
@Test
public void testFindUsers() throws IOException {
SqlSession session= MybatisUntil.openSession();
StuDao stuDao=session.getMapper(StuDao.class);
Student stu=stuDao.FindStu(1);
session.close();
System.out.println(stu);
}
//查询所有用户信息
@Test
public void testFindUserlist() throws IOException {
SqlSession session=MybatisUntil.openSession();
StuDao stuDao=session.getMapper(StuDao.class);
List<Student> stus=stuDao.FindStus();
System.out.println(stus);
}
//插入单个用户
@Test
public void testInsertUser() throws IOException {
SqlSession session=MybatisUntil.openSession();
StuDao stuDao=session.getMapper(StuDao.class);
Student stu=new Student();
stu.setAddress("开封市");
stu.setEmail("1872340000@qq.com");
stu.setPassword("123456");
stu.setClazznumber(20181002);
stu.setClazzname("测试二班");
stu.setPhone("18237880000");
stu.setSex(1);
stu.setUsername("杨贺");
stuDao.InsertStu(stu);
session.commit();//插入用户注意要提交
session.close();
}
//删除单个用户
@Test
public void testDeleteUser() throws IOException {
SqlSession session=MybatisUntil.openSession();
StuDao stuDao=session.getMapper(StuDao.class);
stuDao.DeleteStu(8);
session.commit(); //删除用户需要提交
session.close();
}
//更新单个用户
@Test
public void testUpdateUser() throws IOException {
SqlSession session=MybatisUntil.openSession();
StuDao stuMapper=session.getMapper(StuDao.class);
Student Stu=new Student();
Stu.setId(1);//用于查找要更新的用户
Stu.setUsername("杨贺");
Stu.setAddress("河南省开封市");
Stu.setEmail("0000@163.com");
Stu.setPhone("1653");
Stu.setClazznumber(2017151101);
Stu.setClazzname("测试一班");
Stu.setSex(1);
Stu.setPassword("12345666");
stuMapper.UpdateStu(Stu);
session.commit(); //更新用户需要提交
session.close();
}
}
 

10.完成。

posted @ 2019-10-20 18:03  Cool_Yang  阅读(317)  评论(0编辑  收藏  举报