目录
2.2 Service增加 @Service注解,UserDao属性添加@Resource注解
2.3 修改beans.xml文件,引入context空间,使用组件扫描。
3.4 配置spring配置文件spring-config.xml
一、Spring简单示例
1.1 创建springdemo模块
1.2 添加pom依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
</dependencies>
1.3 创建HelloService.java文件
package com.jackyan.springdemo.service;
public class HelloService {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void sayHello() {
System.out.println(message);
}
}
1.4 创建spring配置文件bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="ws" class="com.jackyan.springdemo.service.HelloService">
<property name="message" value="hello world!"/>
</bean>
</beans>
1.5 创建测试代码
package com.jackyan.springdemo;
import com.jackyan.springdemo.service.HelloService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
HelloService ws = (HelloService)ac.getBean("ws");
ws.sayHello();
}
}
1.6 测试结果
1.7 引入dao层
创建UserDao
package com.jackyan.springdemo.dao;
public class UserDao {
/**
* 模拟插入数据
*/
public void insert() {
System.out.println("insert data!");
}
}
建立service和dao的关联,只需要配置get方法
...
public class HelloService {
private String message;
private UserDao userDao; // 建立service和dao的关联
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
...
修改spring配置文件bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="ws" class="com.jackyan.springdemo.service.HelloService">
<property name="message" value="hello world!"/>
<property name="userDao" ref="userDao"/>
</bean>
<bean id="userDao" class="com.jackyan.springdemo.dao.UserDao"/>
</beans>
1.8 引入dao层后测试
二、Spring注解使用
2.1 UserDao增加@Repository注解
package com.jackyan.springdemo.dao;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public class UserDao {
/**
* 模拟插入数据
*/
public void insert() {
System.out.println("insert data!");
}
}
2.2 Service增加 @Service注解,UserDao属性添加@Resource注解
package com.jackyan.springdemo.service;
import com.jackyan.springdemo.dao.UserDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("ws")
public class HelloService {
private String message = "hello world!";
@Resource(name = "userDao")
private UserDao userDao; // 建立service和dao的关联
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void sayHello() {
System.out.println(message);
userDao.insert();
}
}
2.3 修改beans.xml文件,引入context空间,使用组件扫描。
<?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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.jackyan.springdemo"/>
</beans>
2.4 测试结果
三、spring 整合mybatis
3.1 创建模块,引入maven支持
3.2 添加pom依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
</dependencies>
3.3 创建项目包
com.jackyan.springmybatisdemo.dao
com.jackyan.springmybatisdemo.service
com.jackyan.springmybatisdemo.util
3.4 配置spring配置文件spring-config.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://192.168.56.101/mybatis"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
<property name="maxPoolSize" value="10"/>
<property name="minPoolSize" value="2"/>
<property name="initialPoolSize" value="2"/>
<property name="acquireIncrement" value="2"/>
</bean>
</beans>
3.4 编写测试类测试获取连接
public class TestDataSource {
@Test
public void testConn() throws SQLException {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
DataSource dataSource = (DataSource)ac.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
}
3.5 成功获取连接
3.6 创建beans
与“SSM学习总结之mybatis快速入门”的bean相同
public class User {
private Integer id;
private String name;
private Integer age;
private List<Order> orders;
...
public class Order {
private Integer id;
private String orderNo;
private User user; // 与用户建立关联
private List<Item> items; // 与Item建立关联
...
public class Item {
private Integer id;
private String itemName;
private Order order; // 与订单建立关联
3.7 添加Mapper.xml映射文件
UserMapper.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="users">
<!-- 定义insert语句 -->
<insert id="insert">
insert into users(name,age) values(#{name},#{age})
</insert>
<update id="update">
update users set name = #{name}, age = #{age} where id = #{id}
</update>
<!-- 查询一个用户的信息 -->
<select id="selectOne" parameterType="int" resultMap="RM_User">
select
u.id uid,
u.name uname,
u.age uage,
o.id oid,
o.orderno oorderno
from users u left join orders o
on u.id = o.uid
where u.id = #{id}
</select>
<!-- 查询多个用户的信息 -->
<select id="selectAll" resultMap="RM_User">
select
u.id uid,
u.name uname,
u.age uage,
o.id oid,
o.orderno oorderno
from users u left join orders o
on u.id = o.uid
</select>
<!-- 删除 -->
<delete id="delete">
delete from users where id = #{id}
</delete>
<resultMap id="RM_User" type="_User">
<id property="id" column="uid"/>
<result property="name" column="uname"/>
<result property="age" column="uage"/>
<collection property="orders" ofType="_Order">
<id property="id" column="oid"/>
<result property="orderNo" column="oorderno"/>
</collection>
</resultMap>
</mapper>
OrderMapper.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="orders">
<insert id="insert" >
insert into orders(orderNo,uid) values(#{orderNo},#{user.id})
</insert>
<!-- 查询一行 -->
<select id="selectOne" parameterType="int" resultMap="RM_Order">
SELECT
o.id oid,
o.orderno oorderno,
o.uid ouid,
u.name uname,
u.age uage,
i.id iid,
i.itemname iitemname
FROM orders o
LEFT JOIN users u ON o.uid = u.id
left join items i on o.id = i.oid
where o.id = #{id}
</select>
<!-- 查询多行 -->
<select id="selectAll" resultMap="RM_Order">
SELECT
o.id oid,
o.orderno oorderno,
o.uid ouid,
u.name uname,
u.age uage,
i.id iid,
i.itemname iitemname
FROM orders o
LEFT JOIN users u ON o.uid = u.id
left join items i on o.id = i.oid
</select>
<!-- 自定义结果映射 -->
<resultMap id="RM_Order" type="_Order">
<id property="id" column="oid"/>
<result property="orderNo" column="oorderno"/>
<association property="user" javaType="_User">
<id property="id" column="ouid" />
<result property="name" column="uname" />
<result property="age" column="uage" />
</association>
<collection property="items" ofType="_Item">
<id property="id" column="iid"/>
<result property="itemName" column="iitemname"/>
</collection>
</resultMap>
</mapper>
3.8 添加mybatis-config.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>
<typeAliases >
<!-- 给类起别名 -->
<typeAlias type="com.jackyan.springmybatisdemo.bean.User" alias="_User"/>
<typeAlias type="com.jackyan.springmybatisdemo.bean.Order" alias="_Order"/>
<typeAlias type="com.jackyan.springmybatisdemo.bean.Item" alias="_Item"/>
</typeAliases>
<!-- 引入映射文件 -->
<mappers>
<mapper resource="UserMapper.xml"></mapper>
<mapper resource="OrderMapper.xml"></mapper>
</mappers>
</configuration>
3.9 创建Dao接口和实现类
BaseDao.java
package com.jackyan.springmybatisdemo.dao;
/**
* Dao接口类
* @param <T>
*/
public interface BaseDao<T> {
// 插入数据
public void insert(T t);
// 更新数据
public void update(T t);
// 删除数据
public void delete(Integer id);
// 根据id查询数据
public void selectOne(Integer id);
// 查询所有数据
public void selectAll();
}
UserDao.java
package com.jackyan.springmybatisdemo.dao;
import com.jackyan.springmybatisdemo.bean.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao extends SqlSessionDaoSupport implements BaseDao<User> {
public void insert(User user) {
getSqlSession().insert("users.insert", user);
}
public void update(User user) {
getSqlSession().update("users.update", user);
}
public void delete(Integer id) {
getSqlSession().delete("users.delete", id);
}
public void selectOne(Integer id) {
getSqlSession().selectOne("users.selectOne", id);
}
public void selectAll() {
getSqlSession().selectList("users.selectAll");
}
}
3.10 创建Service接口和实现类
BaseService.java
package com.jackyan.springmybatisdemo.service;
public interface BaseService<T> {
// 插入数据
public void insert(T t);
// 更新数据
public void update(T t);
// 删除数据
public void delete(Integer id);
// 根据id查询数据
public void selectOne(Integer id);
// 查询所有数据
public void selectAll();
}
BaseServiceImpl.java
package com.jackyan.springmybatisdemo.service.impl;
import com.jackyan.springmybatisdemo.dao.BaseDao;
import com.jackyan.springmybatisdemo.service.BaseService;
public abstract class BaseServiceImpl<T> implements BaseService<T> {
private BaseDao<T> dao;
public void setDao(BaseDao<T> dao) {
this.dao = dao;
}
public void insert(T t) {
dao.insert(t);
}
public void update(T t) {
dao.update(t);
}
public void delete(Integer id) {
dao.delete(id);
}
public void selectOne(Integer id) {
dao.selectOne(id);
}
public void selectAll() {
dao.selectAll();
}
}
UserService.java(方便业务扩展)
package com.jackyan.springmybatisdemo.service;
import com.jackyan.springmybatisdemo.bean.User;
public interface UserService extends BaseService<User> {
}
UserServiceImpl.java(传入业务Dao)
package com.jackyan.springmybatisdemo.service.impl;
import com.jackyan.springmybatisdemo.bean.User;
import com.jackyan.springmybatisdemo.dao.BaseDao;
import com.jackyan.springmybatisdemo.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
/**
* 重写该方法,注入指定的Dao对象
*/
@Override
@Resource(name = "userDao")
public void setDao(BaseDao<User> dao) {
super.setDao(dao);
}
}
3.11 更新完善spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd" default-autowire="byType">
<!-- 配置事务特征 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Service.*(..))" />
</aop:config>
<!-- 扫描包 -->
<context:component-scan base-package="com.jackyan.springmybatisdemo" />
<!-- 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://192.168.56.101/mybatis?user=root&password=root"/>
<!-- <property name="user" value="root"/> -->
<!-- <property name="password" value="root"/> -->
<property name="maxPoolSize" value="10"/>
<property name="minPoolSize" value="2"/>
<property name="initialPoolSize" value="2"/>
<property name="acquireIncrement" value="2"/>
</bean>
<!-- mybatis整合spring的核心类。 -->
<bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 指定mybatis配置文件 -->
<property name="configLocation" value="mybatis-config.xml"/>
</bean>
<!-- 数据源事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
3.12 编写测试代码测试
/**
* 测试插入数据
* @throws Exception
*/
@Test
public void testInsert() throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
UserService us = (UserService)ac.getBean("userService");
User u = new User();
u.setName("jerry");
u.setAge(12);
us.insert(u);
}
/**
* 查询全部数据
* @throws Exception
*/
@Test
public void testSelectAll() throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
UserService us = (UserService)ac.getBean("userService");
List<User> users = us.selectAll();
for (User user : users) {
System.out.println(user);
}
}