以它们之前的一个简单用例作为实例。
一个简单的能跑起来的实例。原文网址。非常好的例子。
http://www.open-open.com/lib/view/open1390534380648.html
运行结果图
项目结构图
关于源代码原链接中已经给出了,能够备份到其他存储位置再好不过了。
首先开始pom文件
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hskj</groupId> <artifactId>maven_spring</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- JUnit testing framework --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.6.RELEASE</version> </dependency> <!-- Spring AOP dependency --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <!-- MySQL database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> </dependencies> </project>
来看看存放在src/main/resources的配置文件吧。
数据库相关属性配置config.properties
db.driverClass=org.gjt.mm.mysql.Driver db.jdbcUrl=jdbc:mysql://localhost:3306/test db.user=root db.password=root # db.initialPoolSize=20 db.maxIdleTime=60 db.maxPoolSize=200 db.minPoolSize=50 # db.acquireIncrement=3 db.acquireRetryDelay=1000 db.acquireRetryAttempts=30 db.breakAfterAcquireFailure=false 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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 加载配置文件 --> <context:property-placeholder location="config.properties" /> <!-- 指定spring注解注入层--> <context:component-scan base-package="com.hskj" /> <!-- 数据库连接池管理 --> <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${db.driverClass}"></property> <property name="jdbcUrl" value="${db.jdbcUrl}"></property> <property name="user" value="${db.user}"></property> <property name="password" value="${db.password}"></property> <property name="initialPoolSize" value="${db.initialPoolSize}"></property> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime" value="${db.maxIdleTime}"></property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize" value="${db.maxPoolSize}"></property> <property name="minPoolSize" value="${db.minPoolSize}"></property> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement" value="${db.acquireIncrement}"></property> <!--两次连接中间隔时间,单位毫秒。Default: 1000 --> <property name="acquireRetryDelay" value="${db.acquireRetryDelay}"></property> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}"></property> <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false--> <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}"></property> </bean> <!-- ================================事务相关控制================================================= --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="c3p0DataSource"></property> </bean> <tx:advice id="userTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="find*" propagation="SUPPORTS"/> <tx:method name="get*" propagation="SUPPORTS"/> <tx:method name="select*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pc" expression="execution(public * com.hskj.service.*.*(..))" /> <!--把事务控制在Service层--> <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" /> </aop:config> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="c3p0DataSource" /> <property name="configLocation" value="MyBatis-Configuration.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.hskj.mapper.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
mybatis的配置MyBatis-Configuration.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> <mappers> <mapper resource="UserDaoMapper.xml"/> </mappers> </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.hskj.mapper.UserMapper"> <parameterMap type="com.hskj.domain.User" id="parameterMapUser"> <parameter property="id"/> <parameter property="name"/> </parameterMap> <resultMap type="com.hskj.domain.User" id="resultMapUser"> <result property="id" column="id"/> <result property="name" column="name"/> </resultMap> <insert id="insertUser" parameterMap="parameterMapUser"> INSERT INTO user(id,name) VALUES(?,?) </insert> <select id="countAll" resultType="int"> select count(*) c from user; </select> <select id="getAllUser" resultMap="resultMapUser"> SELECT * FROM user </select> <select id="getById" parameterType="String" resultMap="resultMapUser"> SELECT * FROM user WHERE id=#{value} </select> <delete id="deleteUser" parameterType="String"> DELETE FROM user WHERE id=#{value} </delete> <update id="updateUser" parameterType="java.util.Map"> UPDATE user SET name=#{name} WHERE id=#{id} </update> </mapper>
之后有六个java主类和一个测试类,看结构图。
User.java
package com.hskj.domain; public class User { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User() { } public User(String id, String name) { super(); this.id = id; this.name = name; } }
UserMapper.java
package com.hskj.mapper; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import com.hskj.domain.User; @Service("userMapper") public interface UserMapper { public int countAll(); public void insertUser(User user); public List<User> getAllUser(); public User getById(String id); public void deleteUser(String id); public void updateUser(Map<String,Object> map); }
UserDao.java
package com.hskj.dao; import java.util.List; import java.util.Map; import com.hskj.domain.User; public interface UserDao { public int countAll(); public void insertUser(User user); public List<User> getAllUser(); public User getById(String id); public void deleteUser(String id); public void updateUser(Map<String,Object> map); }
UserDaoImpl.java
package com.hskj.daoImpl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hskj.dao.UserDao; import com.hskj.domain.User; import com.hskj.mapper.UserMapper; @Service("userDao") public class UserDaoImpl implements UserDao{ @Autowired private UserMapper userMapper; public int countAll() { return this.userMapper.countAll(); } public void insertUser(User user) { this.userMapper.insertUser(user); } public List<User> getAllUser() { return this.userMapper.getAllUser(); } public User getById(String id) { return this.userMapper.getById(id); } public void deleteUser(String id) { this.userMapper.deleteUser(id); } public void updateUser(Map<String, Object> map) { this.userMapper.updateUser(map); } }
UserService.java
package com.hskj.service; import java.util.Map; import com.hskj.domain.User; public interface UserService { public int countAll(); public void insertUser(User user); public void update_insert(Map map,User user); }
UserServiceImpl.java
package com.hskj.serviceImpl; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hskj.dao.UserDao; import com.hskj.domain.User; import com.hskj.service.UserService; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public int countAll() { return this.userDao.countAll(); } public void insertUser(User user) { this.userDao.insertUser(user); throw new RuntimeException("Error"); } public void update_insert(Map map,User user) { this.userDao.updateUser(map); this.userDao.insertUser(user); throw new RuntimeException("Error"); } }
测试类
UserServiceTest.java
import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.hskj.domain.User; import com.hskj.service.UserService; public class UserServiceTest { @Test public void userServiceTest(){ @SuppressWarnings("resource") ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService)context.getBean("userService"); // User user =new User(); // user.setId("003"); // user.setName("樱木滑到"); // // Map map=new HashMap(); // map.put("id", "001"); // map.put("name", "方传子"); // Map map = new HashMap(); // map.put("id", "000012"); // map.put("name", "吴勇"); try { System.out.println(userService.countAll()); // userService.update_insert(map, user); // userService.insertUser(user); //userService.update_insert(map, user); // userService.insertUser(user);// } catch (Exception e) { e.printStackTrace(); } } }