天天看点

Mybatis持久层框架环境搭建,加简单查询,插入数据

Mybatis持久层框架环境搭建

隶属Apache组织的半自动框架(相对于hibernate) Mybatis原理图:

Mybatis持久层框架环境搭建,加简单查询,插入数据

新建一个普通的java工程

导入mybatis和mysql连接数据库所需的包:

mybatis-3.2.8.jar

mysql-connector-java-5.1.34

1.配置mysql数据库    jdbc.username填你自己的数据库用户名  jdbc.password填你自己的数据库密码

新建resource包  再包下创建file 名为jdbc.properties

jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/mysql_demo

jdbc.username=

jdbc.password=

2.建立要映射的对象 student表结构:

Mybatis持久层框架环境搭建,加简单查询,插入数据

这里要根据自己数据库表的结构来创建实体对象 : 新建Student实体类:

public class Student {

    private Integer Sid;

    private String Sname;

    private String Ssex;

    private Integer Sage;

    private Integer Tid;

    public Integer getSid() {

        return Sid;

    }

    public void setSid(Integer sid) {

        Sid = sid;

    }

    public String getSname() {

        return Sname;

    }

    public void setSname(String sname) {

        Sname = sname;

    }

    public String getSsex() {

        return Ssex;

    }

    public void setSsex(String ssex) {

        Ssex = ssex;

    }

    public Integer getSage() {

        return Sage;

    }

    public void setSage(Integer sage) {

        Sage = sage;

    }

    public Integer getTid() {

        return Tid;

    }

    public void setTid(Integer tid) {

        Tid = tid;

    }

}

3.新建dao包 再建StudentMapper接口 public interface StudentMapper {

        //插入了一条数据  返回一   插了两条就返回二

    public int insertStudent(Student student)throws Exception;

    //查询一位学生

    public Student selectOneById(int id) throws Exception;

    //查询所有学生列表

    List<Student> selectAllStudent()throws Exception;

}

4.mybatis的配置文件  设置mybatis,对象要映射到什么地方去

在resource包新建file  名为mybatis-cfg.xml

mybatis-cfg.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="resource/jdbc.properties"/>

    <!--default可以随便写的-->

    <environments default="mybatis-demo">

        <environment id="mybatis-demo">

            <!--type是用什么方式管理事务,假如用了Spring框架管理事务,就填Spring-->

            <transactionManager type="JDBC"></transactionManager>

            <!--这里是用了自带的连接池-->

            <dataSource type="POOLED">

                <!--加载了配置文件之后,要取值-->

                <property name="driver" value="${jdbc.driver}"/>

                <property name="url" value="${jdbc.url}"/>

                <property name="username" value="${jdbc.username}"/>

                <property name="password" value="${jdbc.password}"/>

            </dataSource>

        </environment>

    </environments>

   <!--声明mapper的位置    -->

    <mappers>

        <!--声明mybatis要扫描那个包下面的全部mapper-->

        <package name="dao"/>

    </mappers>

</configuration>

5.在dao包新建file  名为StudentMapper.xml

写数据库和对象的映射所需mapper   和sql语句

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        <!--数据库和对象的映射所需mapper-->

<mapper namespace="dao.StudentMapper">

    <!--type是告诉resultMap  要映射到哪一个javabean-->

    <resultMap id="studentMapper" type="entity.Student">

        <!--column是数据库属性ID对应的是property是实体对象属性ID-->

        <!--<id >  这个是写主键的-->

        <id  property="Sid"  column="Sid" />

        <result property="Sname" column="Sname" />

        <result property="Ssex" column="Ssex" />

        <result property="Tid" column="Tid" />

        <result property="Sage" column="SageNum" />

    </resultMap>

    <!--编写StudentMapper接口里面所需要实现的方法-->

    <insert id="insertStudent"  parameterType="entity.Student">

        INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum) VALUES (#{Sid},#{Sname},#{Ssex},#{Tid},#{Sage})

    </insert>

</mapper>

6.在主函数写

public class Main {

    public static void main(String[] args) throws Exception {

            //加载配置文件  通过io流加载xml文件

         InputStream in= Main.class.getResourceAsStream("resource/mybatis-cfg.xml");

        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);

        SqlSession session= factory.openSession();

        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //创建需要插入的Student对象

        Student student=new Student();

        student.setSid(10);

        student.setSage(12);

        student.setTid(1);

        student.setSsex("男");

        student.setSname("haha");

        mapper.insertStudent(student);

        //需要session.commit  不然数据库是不会发生改变的

        session.commit();

        //关闭会话   避免占用资源

        session.close();

    }

}

demo目录结构:

Mybatis持久层框架环境搭建,加简单查询,插入数据

执行程序前数据库studnet表:

Mybatis持久层框架环境搭建,加简单查询,插入数据

执行程序后  student表:

Mybatis持久层框架环境搭建,加简单查询,插入数据

数据成功插入  可喜可贺O(∩_∩)O

因为mybatis已经搭建好了  所以我们执行查询操作就简答多了

倘若我们想要执行查询操作:

1.修改StudentMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        <!--数据库和对象的映射所需mapper-->

<mapper namespace="dao.StudentMapper">

    <!--type是告诉resultMap  要映射到哪一个javabean-->

    <resultMap id="studentMapper" type="entity.Student">

        <!--column是数据库属性ID对应的是property是实体对象属性ID-->

        <!--<id >  这个是写主键的-->

        <id  property="Sid"  column="Sid" />

        <result property="Sname" column="Sname" />

        <result property="Ssex" column="Ssex" />

        <result property="Tid" column="Tid" />

        <result property="Sage" column="SageNum" />

    </resultMap>

    <!--编写StudentMapper接口里面所需要实现的insertStudent方法-->

    <insert id="insertStudent"  parameterType="entity.Student">

        INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum) VALUES (#{Sid},#{Sname},#{Ssex},#{Tid},#{Sage})

    </insert>

    <!--编写StudentMapper接口里面所需要实现的selectOneById方法-->

    <!--根据studentMapper来映射-->

    <!--Sid=#{id}  花括号里面填id是因为StudentMapper接口里面所需要实现的selectOneById方法的参数是id-->

    <select id="selectOneById" resultMap="studentMapper">

        SELECT * FROM student WHERE Sid=#{id}

    </select>

</mapper>

2.修改主函数:

public class Main {

    public static void main(String[] args) throws Exception {

            //加载配置文件  通过io流加载xml文件

         InputStream in= Main.class.getResourceAsStream("resource/mybatis-cfg.xml");

        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);

        SqlSession session= factory.openSession();

        StudentMapper mapper=session.getMapper(StudentMapper.class);

        //创建需要插入的Student对象

        Student student=new Student();

        //需要session.commit  不然数据库是不会发生改变的

        //查询student表Sid为5号的人

     student=   mapper.selectOneById(5);

        session.commit();

        //关闭会话   避免占用资源

        session.close();

    }

}

自行debug  会发现已经把5号student对象查询成功

倘若我们不查询单个人,我们要查询list集合

1.修改StudentMapper.xml

StudentMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        <!--数据库和对象的映射所需mapper-->

<mapper namespace="dao.StudentMapper">

    <!--type是告诉resultMap  要映射到哪一个javabean-->

    <resultMap id="studentMapper" type="entity.Student">

        <!--column是数据库属性ID对应的是property是实体对象属性ID-->

        <!--<id >  这个是写主键的-->

        <id  property="Sid"  column="Sid" />

        <result property="Sname" column="Sname" />

        <result property="Ssex" column="Ssex" />

        <result property="Tid" column="Tid" />

        <result property="Sage" column="SageNum" />

    </resultMap>

    <!--编写StudentMapper接口里面所需要实现的insertStudent方法-->

    <insert id="insertStudent"  parameterType="entity.Student">

        INSERT INTO student (Sid,Sname,Ssex,Tid,SageNum) VALUES (#{Sid},#{Sname},#{Ssex},#{Tid},#{Sage})

    </insert>

    <!--编写StudentMapper接口里面所需要实现的selectOneById方法-->

    <!--根据studentMapper来映射-->

    <!--Sid=#{id}  花括号里面填id是因为StudentMapper接口里面所需要实现的selectOneById方法的参数是id-->

    <select id="selectOneById" resultMap="studentMapper">

        SELECT * FROM student WHERE Sid=#{id}

    </select>

    <!--查询多人列表  返回list集合-->

    <select id="selectAllStudent" resultMap="studentMapper" >

         SELECT * FROM student

    </select>

</mapper>

2.修改主函数:

public class Main {

    public static void main(String[] args) throws Exception {

            //加载配置文件  通过io流加载xml文件

         InputStream in= Main.class.getResourceAsStream("resource/mybatis-cfg.xml");

        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);

        SqlSession session= factory.openSession();

        StudentMapper mapper=session.getMapper(StudentMapper.class);

        Student student=new Student();

        //需要session.commit  不然数据库是不会发生改变的

        //查询student表Sid为5号的人

        //mybatis自动把查询出的数据,自动映射,封装成对象  大大节省了时间

        //现在看来   写StudentMapper  和StudentMapper.xml都很费时间  在后面,我会在博客里说如何自动生成Mapper和Mapper.xml

        List<Student> studentList=mapper.selectAllStudent();

        session.commit();

        //关闭会话   避免占用资源

        session.close();

    }

}

自行debug执行程序  会发现查询成功了 完结撒花O(∩_∩)O

继续阅读