spring已然成为web开发的主流框架,这个专题主要讲springh中运用Mybatis来作为连接数据库的框架。MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录.
orm工具的基本思想无论是用过的hibernate,mybatis,你都可以法相他们有一个共同点:1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.2. 由sessionfactory 产生 session3. 在session 中完成对数据的增删改查和事务提交等.4. 在用完之后关闭session 。5. 在Java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。
1.环境搭建:
①建立数据库:
创建一个student数据库,再立一个Student表(将stu_id设为主键)- :
②创建maven web工程:
不懂的可以参考这个链接 创建maven web工程
搭建完之后就是这样
③书写配置文件其中pom.xml中配置如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mask</groupId>
<artifactId>MybatisDemo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>MybatisDemo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.4.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.4.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.4.RELEASE</version>
<type>jar</type>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- mysql连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- c3p0数据源 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5-pre10</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.lang -->
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.lang</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!--mybatis-spring整合包,这样就可以通过spring配置bean的方式进行mybatis配置了,
不然需要单独使用mybatis的配置-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
<build>
<finalName>MybatisDemo</finalName>
</build>
</project>
④web容器的配置web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml,classpath*:spring-mybatis.xml</param-value>
</context-param>
<!--
<filter>
<filter-name>ClodewebFilter</filter-name>
<filter-class>com.jplus.filter.ClodewebFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ClodewebFilter</filter-name>
<url-pattern>*.do,*.jsp</url-pattern>
</filter-mapping>
-->
<filter>
<description>字符集过滤器</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description>字符集编码</description>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>spring mvc 配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
⑥applicationContext配置,就是spring容器的配置:applicationContext.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
" >
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 自动扫描(自动注入) -->
<context:component-scan base-package="com.baobaotao.Service" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize"><value>1000000000000000</value></property>
<property name="defaultEncoding"><value>UTF-8</value></property>
</bean>
</beans>
⑦spring mvc配置 spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 自动扫描controller包下的所有类,如果@Controller注入为bean -->
<context:component-scan base-package="com.baobaotao.controller" />
<!-- 以下为SpringMVC配置 -->
<mvc:annotation-driven />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置多文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<!-- 上传文件大小限制为 -->
<value>32505856</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
</beans>
⑧mybatis配置文件 spring-mybatis.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
" >
<!--引入配置文件-->
<context:property-placeholder location="classpath:db.properties" />
<!--数据源配置-->
<!-- c3p0数据源配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/student" />
<property name="user" value="root" />
<property name="password" value="root" />
<!-- 请求超时时间 -->
<property name="checkoutTimeout" value="30000" />
<!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
<property name="idleConnectionTestPeriod" value="30" />
<!-- 连接数据库连接池最大空闲时间 -->
<property name="maxIdleTime" value="30" />
<!-- 连接池初始化连接数 -->
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
<property name="acquireIncrement" value="5" />
</bean>
<!--mybatis与spring的整合,不需要mybatis自己的配置映射文件-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置连接数据库数据源-->
<property name="dataSource" ref="dataSource"/>
<!--配置Mapper文件所在位置-->
<property name="mapperLocations" value="classpath:/mybatis/StudentMapper.xml"/>
</bean>
<!--MapperScannerConfigurer将会扫描basePackage并自动装配-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.baobaotao.Dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--事务管理,这里可以先不忙加入-->
<!--<bean id="transactionManager"-->
<!--class="org.springframework.jdbc.datasource.DataSourceTransactionManager">-->
<!--<property name="dataSource" ref="dataSource"/>-->
<!--</bean>-->
</beans>
二.建立domainc层,controller层,service层,dao层
①domain层,位于com.baobaotao.domain包下
package com.baobaotao.domain;
import java.io.Serializable;
/**
* Date: 2017年4月11日 下午9:59:50
* @author maskwang
* @since JDK 1.6
*/
public class Student implements Serializable {
private int stu_id;
private String name;
private int age;
private int money;
public int getStu_id() {
return stu_id;
}
public void setStu_id(int stu_id) {
this.stu_id = stu_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
@Override
public String toString() {
return "Student [stu_id=" + stu_id + ", name=" + name + ", age=" + age + ", money=" + money + "]";
}
}
②service层,位于com.baobaotao.Service包下
package com.baobaotao.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baobaotao.Dao.StudentDao;
import com.baobaotao.domain.Student;
/**
* Date: 2017年4月12日 上午8:05:17
* @author maskwang
* @since JDK 1.6
*/
@Service
public class StudentService {
@Autowired
StudentDao studentDao;
public Student getStudent(int id) {
// TODO Auto-generated method stub
return studentDao.getStudent(id);
}
public void deleteStudent(int id) {
studentDao.deleteStudent(id);
}
public void updateStudent(Student stu) {
studentDao.updateStudent(stu);
}
public List<Student> getAllStudent() {
// TODO Auto-generated method stub
return studentDao.getAllStudent();
}
public void insertStudent(Student stu) {
studentDao.insertStudent(stu);
}
}
③.Dao层,位于com.baobaotao.Dao层
package com.baobaotao.Dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.baobaotao.domain.Student;
/**
* Date: 2017年4月11日 下午10:01:47
* @author maskwang
* @since JDK 1.6
*/
@Repository
public interface StudentDao {
public Student getStudent(int id);
public void deleteStudent(int id);
public void updateStudent(Student stu);
public List<Student> getAllStudent();
public void insertStudent(Student stu);
}
④controller层,位于com.baobaotao.controller层
package com.baobaotao.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baobaotao.Service.StudentService;
import com.baobaotao.domain.Student;
/**
* Date: 2017年4月11日 下午10:15:26
* @author maskwang
* @since JDK 1.6
*/
@Controller
public class StudentController {
@Autowired
StudentService studentService;
@RequestMapping(value = "/loginCheck.html")
public void getAllStudent(){
System.out.println("hello");
//Student stu=studentService.getStudent(123);
// List<Student> list=studentService.getAllStudent();
// System.out.println(list);
Student stu=new Student();
stu.setAge(100);
stu.setMoney(1000);
stu.setName("hello");
stu.setStu_id(126);
studentService.insertStudent(stu);
stu.setName("sb");
studentService.updateStudent(stu);
// studentService.deleteStudent(126);
}
}
④对应的StudentMapper文件位于clathpath:/mybatis/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">
<mapper namespace="com.baobaotao.Dao.StudentDao">
<resultMap id="User" type="com.baobaotao.domain.Student">
<result property="stu_id" column="stu_id" jdbcType="VARCHAR"/>
<result property="name" column="stu_name" jdbcType="VARCHAR"/>
<result property="age" column="stu_age" jdbcType="VARCHAR"/>
<result column="stu_mon" property="money" jdbcType="INTEGER"/>
</resultMap>
<select id="getStudent" resultMap="User" >
SELECT *FROM student WHERE stu_id=#{0}
</select>
<!-- 获取所有学生 -->
<select id="getAllStudent" resultMap="User" >
SELECT *FROM student
</select>
<!-- 添加学生 -->
<insert id="insertStudent" parameterType="com.baobaotao.domain.Student"
useGeneratedKeys="true" keyProperty="id">
insert into student(stu_id,stu_name,stu_age,stu_mon)
values(#{stu_id},#{name},#{age},#{money})
</insert>
<delete id="deleteStudent" parameterType="int">
delete from student where stu_id=#{id}
</delete>
<update id="updateStudent" parameterType="com.baobaotao.domain.Student" >
update student set stu_id=#{stu_id},stu_name=#{name},stu_age=#{age},stu_mon=#{money} where stu_id=#{stu_id}
</update>
</mapper>