1. 动态数据库类
在Chamt工程中创建一个叫做dynamiDataSource的类,用于处理从Common中读取到的数据库配置
package com.china.init;
import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.springframework.stereotype.Component;
import com.common.datasource.DsManager;
import com.common.initor.config.SystemConfig;
@Component
public class ChamtInit {
private SystemConfig config;
private DsManager dsmanager;
@PostConstruct
void init() throws NamingException {
Context initContext = new InitialContext();
config = (SystemConfig)initContext.lookup("java:comp/env/cham/test");
dsmanager = (DsManager)initContext.lookup("java:comp/env/cham/dsmanager");
}
public SystemConfig getConfig() {
return config;
}
public DsManager getDsmanager() {
return dsmanager;
}
}
package com.china.db;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import com.china.init.ChamtInit;
@Component(value="dynamicDataSource")
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return "database-arg";//此处必须返回当前使用的数据库的名称,否则会包lookup[null]错误
}
@Autowired
public void init(ChamtInit config) {
Map<Object, Object> map = new HashMap<Object, Object>();
DataSource db = config.getDsmanager().getDataSource("database-arg");
map.put("database-arg", db);//要用到的数据源的名称
super.setTargetDataSources(map);//connection交给mybatis处理
}
}
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<!-- <context:component-scan base-package="com.baobaotao.dao"/>
<context:component-scan base-package="com.baobaotao.service"/> -->
<context:component-scan base-package="com.china.db"/>
<context:component-scan base-package="com.china.init"/>
<!-- begin:add by beitian for spring-mybatis test on 2018-06-12 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dynamicDataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dynamicDataSource"/>
<property name="mapperLocations" value="classpath:com/china/db/mapper-usersData.xml"/>
<property name="configLocation" value="classpath:com/china/db/cfg-mybatis.xml"/>
</bean>
<bean id="sqlsessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- end :add by beitian for spring-mybatis test on 2018-06-12 -->
</beans>
mapper-usersData.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.chamt.mybatis.users">
<select id="getUsers" parameterType="int" resultType ="type_user">
<![CDATA[
select id, name, age from users where id=#{id}
]]>
</select>
<!--Begin: 在users表中插入数据 -->
<insert id="insertUser" parameterType="type_user" >
<![CDATA[
insert into users (id,name,age) values(#{id},#{name},#{age})
]]>
</insert>
<!-- End: 在users表中插入数据 -->
<!--Begin: 在users表中修改数据 -->
<update id="updateUser" parameterType="type_user" >
<![CDATA[
update users set name=#{name},age=#{age} where id=#{id}
]]>
</update>
<!-- End: 在users表中修改数据 -->
<!--Begin: 在users表中删除数据 -->
<delete id="deleteUser" parameterType="type_user" >
<![CDATA[
delete users where id=#{id}
]]>
</delete>
<!--End: 在users表中删除数据 -->
</mapper>
cfg-mybatis.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.china.db.User" alias="type_user"/>
</typeAliases>
</configuration>
3. 对应的数据库表结构及对应的spring各个层
本帖中所涉及到的表示users表,其结构如下图
users表对应的java类
package com.china.db;
public class User {
private int id;
private String name;
private int age;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
Dao层
package com.china.db;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserDao extends SqlSessionDaoSupport {
@Autowired
public final void init(SqlSessionTemplate template) {
super.setSqlSessionTemplate(template);
}
//Begin: 在users表中查询一条记录 on 2018-06-16
public User getUser(int id) {
return super.getSqlSession().selectOne("com.chamt.mybatis.users.getUsers", id);
}
//End : 在users表中查询一条数据 on 2018-06-16
//Begin: 在users表中插入一条记录 on 2018-06-16
public void insertUser(User user) {
super.getSqlSession().insert("com.chamt.mybatis.users.insertUser", user);
}
//End : 在users表中插入一条数据 on 2018-06-16
//Begin:修改users表中的某条指定的数据 on 2018-06-16
public void updateUser(User user) {
super.getSqlSession().update("com.chamt.mybatis.users.updateUser", user);
}
//End:修改users表中的某条指定的数据 on 2018-06-16
//Begin:修改users表中的删除某条指定的数据 on 2018-06-16
public void deleteUser(User user) {
super.getSqlSession().delete("com.chamt.mybatis.users.deleteUser", user);
}
//End:修改users表中的删除某条指定的数据 on 2018-06-16
}
Controller层
package com.china.web;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.china.db.User;
import com.china.db.UserDao;
import com.common.datasource.DsManager;
@Controller
public class LoginController
{
private Logger logger = Logger.getLogger(LoginController.class);
@Autowired
private UserDao userDao;
@RequestMapping(value="/index.html")
public String loginPage() throws NamingException
{
System.out.println("+++++++++hello world, hello china+++++++++++");
User user = this.userDao.getUser(1);
System.out.println(user);
//insert();
//this.update();
this.delete();
return "login";
}
@RequestMapping(value="/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request)
{
System.out.println("========loginCheck=========");
return new ModelAndView("main");
}
//Begin: 在users表中插入一条记录 on 2018-06-16
private void insert() {
User user = new User(3, "beitian",30);
userDao.insertUser(user);
}
//End : 在users表中插入一条数据 on 2018-06-16
//Begin:修改users表中的某条指定的数据 on 2018-06-16
private void update() {
User user = new User(3, "meixi", 33);
this.userDao.updateUser(user);
}
//End:修改users表中的某条指定的数据 on 2018-06-16
//Begin:修改users表中的某条指定的数据 on 2018-06-16
private void delete() {
User user = new User(3, "meixi", 33);
this.userDao.deleteUser(user);
}
//End:修改users表中的某条指定的数据 on 2018-06-16
}
如此则可以通过http://ip:port/chamt/index 消息可以实现对数据库中的users表进行增删改查。
6. 所涉及到的jar包
spring和mybatis的各个版本需要配套本工程中用的jar包为
commons-collections.jar
commons-dbcp-1.2.2.jar
commons-pool-1.3.jar
ojdbc14.jar
mybatis-3.4.1.jar
mybatis-spring-1.3.1.jar
以及其他spring原带包