Spring整合Mybatis

来源:互联网 发布:java抢红包程序 编辑:程序博客网 时间:2024/06/05 19:42

Spring整合Mybatis

第一步:创建数据库表

本项目使用的是H2数据库,轻量级数据库,无需安装可直接运行。但是维护数据库,进行建表,增删改查操作时就得安装。数据库很小,就几M,很适合java初学者使用。

安装成功以后双击运行,会自动打开网页,不要急着点连接,上方可以切换语言,重点是要记住JDBC URL

H2数据库登录界面

注意:h2数据库URL若只填地址的话,只能有一个应用程序访问,也就是说,如果你这样填写jdbc:h2:file:~/.h2/StudentManager1.0,那么你网页连接了数据库,那么你的应用程序就不能访问,否则会报错,所以后面应该添加参数;AUTO_SERVER=TRUE,注意有个分号。

连接,建表。

CREATE TABLE `student` (  `id` varchar(255) NOT NULL,  `nickname` varchar(255) DEFAULT NULL,  `name` varchar(255) DEFAULT NULL,  `sex` varchar(255) DEFAULT NULL,  `birthday` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,  `place` varchar(255) DEFAULT NULL,  `dept` varchar(255) DEFAULT NULL,  `clazz` varchar(255) DEFAULT NULL,  `phoneNum` varchar(255) DEFAULT NULL,  `idCard` varchar(255) CHARACTER SET utf8 DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;

表结构
(表结构)

第二步:创建java项目

本项目使用的是maven创建项目,可以去官网下载安装包,配置环境变量,MyEclipse有插件可以直接创建maven项目。
MyEclipse创建maven项目

本项目创建的是普通的java项目所以只有两个源码包。
项目结构

也可以不使用maven创建java项目,只不过导入jar包麻烦了点,需要自己去官网一个个下载,还有各种包的依赖比较麻烦,有可能多导入了包,所以用maven还是比较方便的。

第三步:导入所需jar包

1、 Mybatis(mybatis包)
2、 jdbc
3、 h2(h2数据库包)
4、 spring-core(spring核心包)
5、 spring-context
6、 mybatis-spring(mybatis整合spring包)
7、 spring-jdbc(spring对jdbc依赖包)

若maven项目可从maven中央仓库搜索所需包
maven中央仓库

在pom.xml中dependences标签中直接添加如下代码

<dependency>     <groupId>org.mybatis</groupId>        <artifactId>mybatis</artifactId>     <version>3.4.4</version>    </dependency>    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.37</version>    </dependency>         <dependency>        <groupId>com.h2database</groupId>        <artifactId>h2</artifactId>        <version>1.4.196</version>    </dependency>     <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-core</artifactId>        <version>4.3.9.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>4.3.9.RELEASE</version>    </dependency>    <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis-spring</artifactId>        <version>1.3.1</version>    </dependency>    <dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-jdbc</artifactId>    <version>4.3.9.RELEASE</version></dependency>

添加之后maven会自动帮你把jar添加到你的项目中,也会把它依赖的包添加进来。
jar包结构

第四步:编写代码

App.java

public class App {    public static void main(String[] args)   {        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");        StudentMapper studentMapper = (StudentMapper)context.getBean("studentMapper");        System.out.println(studentMapper.selectStudent("20141737"));    }}

Student.java

public class Student {    private String id;    private String nickname;    private String name;    private String sex;    private Date birthday;    private String place;    private String dept;    private String clazz;    private String phoneNum;    private String idCard;    …    Sets and gets……….}

StudentMapper.java

public interface StudentMapper {    public void add(Student student);    public void delete(Student student);    public void update(Student student);    public Student selectStudent(String id);}

StudentMapperImpl.java

public class StudentMapperImpl implements StudentMapper {    private SqlSessionFactory sqlSessionFactory;    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {        this.sqlSessionFactory = sqlSessionFactory;    }    public void add(Student student) {  }    public void delete(Student student) {}    public void update(Student student) {}    public Student selectStudent(String id) {        SqlSession session = sqlSessionFactory.openSession();        Student student =  (Student)session.selectOne("com.huagege.dao.StudentMapper.selectStudent", "20141737");        session.commit();        session.close();        return student;    }}

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"><!--   namespace对应的是dao接口 --><mapper namespace="com.huagege.dao.StudentMapper">  <select id="selectStudent" resultType="com.huagege.bean.Student">    select * from student where id = #{id}  </select></mapper>

beans.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!-- 配置该属性,sqlSessionFactory会自动读取mapper配置文件 -->        <property name="mapperLocations" value="com/huagege/bean/*.xml" />        <property name="dataSource" ref="dataSource" />    </bean>    <bean id="dataSource"       class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="com.mysql.jdbc.Driver" />        <property name="url"    value="jdbc:h2:file:~/.h2/StudentManager1.0;AUTO_SERVER=TRUE" />        <property name="username" value="sa" />        <property name="password"  value=""/>    </bean>    <bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">        <property name="mapperInterface" value="com.huagege.dao.StudentMapper" />        <property name="sqlSessionFactory" ref="sqlSessionFactory" />    </bean> </beans>

运行app.java,运行成功


配置文件

mybatis映射文件
配置文件中对应的接口映射应与namespace一样,也就是说namespace中应该填写的是dao接口的全类名。
mapper映射关系

Spring配置文件beans.xml
Spring整合mybatis中最重要的两个配置,一个是DataSource,一个是sqlsessionfactory。

DataSource是数据库的数据源,里面可以配置数据库中的各种参数,比如最大连接数,空闲连接等。本项目中只简单的配置了URL与账号密码。

<bean id="dataSource"       class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="com.mysql.jdbc.Driver" />        <property name="url"    value="jdbc:h2:file:~/.h2/StudentManager1.0;AUTO_SERVER=TRUE" />        <property name="username" value="sa" />        <property name="password"  value=""/>    </bean>

Sqlsessionfactory是生成sqlsession的工厂,一个数据库连接对应一个工厂,若你项目只使用一个数据库,那么整个项目只需要一个sqlsessionfactory,所以它需要配置到我们的bean中来。

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!-- -->        <property name="mapperLocations" value="com/huagege/bean/*.xml" />        <property name="dataSource" ref="dataSource" />    </bean>

其中mapperLocation配置可以使sqlsessionfactory自动扫描读取XXXMapper.xml文件


新手学习,仅供参考,源码下载https://github.com/huagegege/Spring-mybatis.git

原创粉丝点击