用java操作数据库,一个JdbcUtil就搞定了。
如:Mybatis入门,从一个简单的JdbcUtil开始
但是,这会有什么问题呢?问题很多,非常多,哈哈。
ORM的出现就是这了解决这些问题,比如经典强大的Mybatis(曾用名:ibatis)。
具体解决了什么问题,后续再讲。先来看看,一个简单的demo。
99%的情况下,mybatis都是集成在springmvc或springboot里使用。
我们就看springmvc如何集成它吧。
**
首先,一些配置文件
**
包括spring的配置和mybatis的配置,来看看有哪些吧
- web项目的
web.xml
在tomcat启动的时候加载,主要配置spring容器的监听和springmvc的servlet
<?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>
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-application.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- ContextconfigLocation配置springmvc加载的配置文件 适配器、处理映射器等 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解决post乱码问题的过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
ContextLoaderListener
是spring容器初始化的入口,使用配置文件classpath:spring-application.xml
进行初始化
DispatcherServlet
是springmvc容器初始化的入口,使用配置文件classpath:spring-mvc.xml
进行初始化
- springmvc的配置文件
spring-mvc.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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置扫描Controller的包 -->
<context:component-scan base-package="com.rice.mvc.controller"/>
<!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
<mvc:annotation-driven />
<!-- 这里设置静态的资源 -->
<!-- <mvc:default-servlet-handler /> -->
<mvc:resources location="/ui/" mapping="/ui/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/img/" mapping="/img/**" />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置上传文件数据解析器 -->
<!-- <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
</bean> -->
</beans>
主要就是配置Controller的包,和注册Handler,还有一些jsp页面的解析器,和静态资源,和上传文件的解析器,常用的就这些,当然还有其他的配置,可以用到了再加。
- spring的配置文件
spring-application.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 激活annotation功能
<context:annotation-config />-->
<!-- 激活annotation功能
<context:spring-configured />-->
<!-- 引入jdbc配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/*.properties</value>
</list>
</property>
</bean>
<!-- 自动扫描注解的bean -->
<context:component-scan base-package="com.rice.mvc.service.*" />
<import resource="classpath:spring/spring-datasource.xml" />
<import resource="classpath:spring/spring-transaction.xml" />
</beans>
主要配置待初始化的bean目录,也就是我们的service层。以及引入其他的spring配置文件
- 数据源配置文件
spring-datasource.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 配置数据源 com.alibaba.druid.pool.DruidDataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://rm-wz9n1e39tno3o4x14do.mysql.rds.aliyuncs.com:3306/rice_dev?useSSL=false&useUnicode=true&characterEncoding=UTF8" />
<property name="username" value="rice" />
<property name="password" value="abc123" />
</bean>
<!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.rice.mvc.dao" />
</bean>
<!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" />
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
</bean>
</beans>
主要就是配置数据源了,以及dao目录、mybatis配置文件和mapper文件目录
- 事务管理配置
spring-transaction.xml
使用spring来管理事务,配置如下
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 事务对象 -->
<bean name="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启用事务 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<tx:annotation-driven transaction-manager="transactionManager"/>
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.rice.mvc.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
</beans>
主要就是配置切面拦截我们service层的方法,根据方法名称使用不同的事务传播属性。当然,不在这里配置也是可以的,在需要事务的方法加上注解
@Transactional
就可以了。个人感觉注解的方式更方便。
- mybatis配置文件
mybatis-config.xml
这是Mybatis必须的配置文件,如下
<?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>
<!-- 基础设置 -->
<settings>
<!-- changes from the defaults,全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<typeAliases>
<typeAlias alias="string" type="java.lang.String" />
<typeAlias alias="long" type="java.lang.Long" />
<typeAlias alias="int" type="java.lang.Integer" />
</typeAliases>
</configuration>
这里可以配置很多选项,可以根据需要配置,官方文档很详细
Mybatis configuration 官网配置
- mybatis的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.rice.mvc.dao.BsUserInfoDao" >
<resultMap type="com.rice.mvc.domain.BsUserInfo" id="UserRltMap">
<result column="user_id" property="userId" jdbcType="VARCHAR" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="login_no" property="loginNo" jdbcType="VARCHAR" />
<result column="login_pwd" property="loginPwd" jdbcType="VARCHAR" />
<result column="contact_phone" property="contactPhone" jdbcType="VARCHAR" />
<result column="contact_email" property="contactEmail" jdbcType="VARCHAR" />
<result column="contact_addr" property="contactAddr" jdbcType="VARCHAR" />
<result column="status" property="status" jdbcType="VARCHAR" />
<result column="is_edit" property="isEdit" jdbcType="VARCHAR" />
<result column="remark" property="remark" jdbcType="VARCHAR" />
<result column="create_id" property="createId" jdbcType="VARCHAR" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="update_id" property="updateId" jdbcType="VARCHAR" />
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
</resultMap>
<sql id="selectAllColumn">
u.user_id,
u.user_name,
u.login_no,
u.login_pwd,
u.contact_phone,
u.contact_email,
u.contact_addr,
u.status,
u.is_edit,
u.remark,
u.create_id,
u.create_time,
u.update_id,
u.update_time
</sql>
<!-- 根据用户id查询用户 -->
<select id="queryByUserId" resultMap="UserRltMap">
select <include refid="selectAllColumn"/>
from bs_user_info u
where u.user_id = #{userId,jdbcType=VARCHAR}
</select>
</mapper>
好了,写了这么多配置文件,总结一下有哪些吧
web.xml
spring-mvc.xml
spring-application.xml
spring-datasource.xml
spring-transaction.xml
mybatis-config.xml
mapper/*.xml
看起来挺多的,但是区分清楚它们各自的功能 ,就很容易理解了。
**
其次,看看java代码
**
都有哪些类呢,mvc分层,无非就是controller,service,dao,bean
- Controller
package com.rice.mvc.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.rice.mvc.service.IBsUserService;
/**
*
* @author rice
*
*/
@Controller
@RequestMapping("/bsuser")
public class BsUserController {
@Resource
private IBsUserService bsUserService;
@RequestMapping("/get/id")
public String queryUserByUserId(String userId) {
System.out.println("queryUserByUserId:" + userId);
String name = bsUserService.queryByUserId(userId).getUserName();
System.out.println(name);
return "welcome";
}
}
- Service
package com.rice.mvc.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.rice.mvc.dao.BsUserInfoDao;
import com.rice.mvc.domain.BsUserInfo;
import com.rice.mvc.service.IBsUserService;
/**
*
* @author rice
*
*/
@Service("bsUserService")
public class BsUserServiceImpl implements IBsUserService {
@Resource
private BsUserInfoDao bsUserInfoDao;
/**
* 根据用户ID查询用户
*
* @param userId
* @return
*/
@Override
public BsUserInfo queryByUserId(String userId) {
return bsUserInfoDao.queryByUserId(userId);
}
}
- dao
package com.rice.mvc.dao;
import org.apache.ibatis.annotations.Param;
import com.rice.mvc.domain.BsUserInfo;
public interface BsUserInfoDao {
/**
* 根据用户ID查询用户
*
* @param userId
* @return
*/
public BsUserInfo queryByUserId(@Param("userId") String userId);
}
- bean
// 忽略了,太简单都不想贴了
**
最后,看看pom文件和工程结构
**
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.rice.mvc</groupId>
<artifactId>rice-mvc</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>rice-mvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>
<build>
<finalName>rice-mvc</finalName>
</build>
</project>
- 工程结构
好了,至此,一个简单的demo跑起来了,实际项目当然会比这更复杂。但是,原理上不会变,都是由此一步一步往上加的。任何一个伟大工程的发展路径都不过如此。