标签: spring MyBatis
将之前的java项目使用了maven管理,就不用导入那么多jar包了(网上很多还是导多了包,强迫症不舒服),maven会帮我们解决依赖问题,pom中每个jar包都有注释,并使用插件解决idea每次刷新都重置jdk的问题,就不需要去setting—>java compiler中修改了
<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.0modelVersion>
<groupId>wenjiegroupId>
<artifactId>web_mavenartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<name>web_maven Maven Webappname>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.1.6.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
dependencies>
<build>
<finalName>web_mavenfinalName>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>2.3.2version>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
project>
MyBatis是一个基于Java的持久层框架,使用简单的 XML或注解用于配置和原始映射,将接口和POJOs映射成数据库中的记录。为了引入它,我们需要在pom中加入以下坐标:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.8version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.1.6.RELEASEversion>
dependency>
然后在resource中添加db.properties数据库配置文件
#数据库连接配置
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
password=123456
#connection pool settings
jdbc.pool.minIdle=3
jdbc.pool.maxIdle=5
jdbc.pool.maxActive=15
jdbc.pool.maxWait=60000
在resource中添加一个spring-mybatis.xml配置文件,都有详细注释:
<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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<context:property-placeholder
ignore-resource-not-found="true"
location="classpath:/db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${password}"/>
<property name="maxActive" value="${jdbc.pool.maxActive}"/>
<property name="maxIdle" value="${jdbc.pool.maxIdle}"/>
<property name="minIdle" value="${jdbc.pool.minIdle}"/>
<property name="maxWait" value="${jdbc.pool.maxWait}"/>
<property name="validationQuery" value="select 1"/>
<property name="testOnBorrow" value="true"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:/mybatis/*Mapper.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wenjie.dao"/>
bean>
beans>
没有必要去指定SqlSessionFactory或SqlSessionTemplate,因为MapperScannerConfigurer将会自动创建装配MapperFactoryBean。但是,如果使 用了一个以上的DataSource,那么自动装配可能会失效。这种情况下,可 以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName 属性来设置正确的bean名称来使用(注意 bean 的名称是必须的,而不是 bean 的引用,因 此,在这里使用value:)
引入多个资源文件的时候,Spring会报错:Could not resolve placeholder
在Spring 3.0中,可以加上ignore-unresolvable写成:
<context:property-placeholder location="xxx.properties" ignore-unresolvable="true" />
<context:property-placeholder location="yyy.properties" ignore-unresolvable="true"
/>
但是在Spring 2.5中,
没有ignore-unresolvable属性,所以就不能使用上面的那种方法去配置,
可以改如下的格式:
id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:/db.properties"/>
<property name="ignoreUnresolvablePlaceholders" value="true" />
在web.xml配置一下spring-mybatis.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>
classpath:/spring-mvc.xml,
classpath:/spring-mybatis.xml
param-value>
init-param>
<load-on-startup>0load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>login.dowelcome-file>
welcome-file-list>
web-app>
然后添加dao(数据持久)层
package com.wenjie.dao;
import com.wenjie.entity.User;
import org.springframework.stereotype.Repository;
/**
* Created by Fate on 2016/7/26.
*/
public interface UserDao {
User findUser(String username, String password);
User findByName(String username);
int createUser(User user);
}
resource下添加mybatis文件夹存放所有映射文件
<mapper namespace="com.wenjie.dao.UserDao">
<resultMap id="User" type="com.wenjie.entity.User">
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="password" column="password" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="VARCHAR"/>
resultMap>
<select id="findUser" resultMap="User">
SELECT *FROM user WHERE name=#{0} and password=#{1}
select>
<insert id="createUser" parameterType="com.wenjie.entity.User">
INSERT INTO user (name,password,age)
VALUES
(#{name},#{password},#{age})
insert>
<select id="findByName" parameterType="java.lang.String" resultMap="User">
SELECT *from user WHERE name=#{username}
select>
mapper>
1> namespace必须指向对应的dao。
<mapper namespace="com.wenjie.dao.UserDao">
2> resultMap是设置一个返回的map,会通过id匹配调用上面设置的resultMap,mybatis会帮你映射,property代表实体类中的字段名,column代表数据库当中的字段名,jdbcType代表数据类型。
3> resultType代表返回类型:
比如:java.lang.String返回String类型参数
4> parameterType代表接收参数类型:
如上面的findByName方法,设置了这个参数之后就可以name=#{username},通过dao层传的参数名取值;
要不然只能和findUser方法一样,只能name=#{0},0代表参数位置,从0开始往下类推。
如果传进来的是实体类,则可以使用实体类当中的字段名取值,比如createUser方法的#{password}
5> parameterMap和resultMap差不多,需要在上面自己配置map。
修改service层并采用(interface接口—impl实现)方式
package com.wenjie.service;
import com.wenjie.entity.User;
/**
* Created by Fate on 2016/7/26.
*/
public interface LoginService {
User login(String username, String password);
}
package com.wenjie.service.impl;
import com.wenjie.dao.UserDao;
import com.wenjie.entity.User;
import com.wenjie.service.LoginService;
import com.wenjie.util.ConnectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by Fate on 2016/7/4.
*/
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
UserDao userDao;
public User login(String name, String password) {
return userDao.findUser(name, password);
}
}
package com.wenjie.service;
/**
* Created by Fate on 2016/7/26.
*/
public interface RegisterService {
boolean register(String username, String password, String age);
}
package com.wenjie.service.impl;
import com.wenjie.dao.UserDao;
import com.wenjie.entity.User;
import com.wenjie.service.RegisterService;
import com.wenjie.util.ConnectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by Fate on 2016/7/4.
*/
@Service
public class RegisterServiceImpl implements RegisterService {
@Autowired
UserDao userDao;
public boolean register(String username, String password, String age) {
User result = userDao.findByName(username);
if (result != null) {
return false;
}
User user = new User();
user.setName(username);
user.setPassword(password);
user.setAge(age);
int re = userDao.createUser(user);
return re == 1;
}
}
然后我们就不需要之前的连接数据库的静态方法ConnectionUtil了,把它删掉,