1
回答
只用mybatis对态切换库的问题

我写了二个方法,帮忙看一下问题,写的有点发闷!谢了!多指出问题来!

SessionFactory

public class SessionFactory{
	private static ThreadLocal<String> threadLocaldb = new ThreadLocal<String>();
	private static String dbid= "development";
	public static void setDbname(String dbname) {
		threadLocaldb.set(dbname);
	}
	public static SqlSession getSession() {
		if(threadLocaldb.get()==null){
			threadLocaldb.set(dbid);
		}
		return DynamicDataSource.getSession(threadLocaldb.get());
	}
	public static void closeSession() {
		DynamicDataSource.closeSession();
	}
	public static void closeDbname(){
		threadLocaldb.set(null);
	}
}

DynamicDataSource

public class DynamicDataSource {
	private static Log log = LogFactory.getLog(DynamicDataSource.class);
	private static String RESOURCE = "myBatis-config.xml";
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
	private static Map<String,SqlSessionFactory> getSessionFactory=setsession();
	public static Map<String,SqlSessionFactory> setsession(){
		Map<String,SqlSessionFactory> sessionFactory=new HashMap<String, SqlSessionFactory>();
		sessionFactory.put("development", getSessionFactory("development"));
		sessionFactory.put("localhost", getSessionFactory("localhost"));
		return sessionFactory;
	}
	public static Reader getResourceAsReader(){
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(RESOURCE);
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		return reader;
	}
	public static SqlSessionFactory getSessionFactory(String environment) {
		
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(getResourceAsReader(),environment);
		return sessionFactory;
	}

	public static SqlSession getSession(String environmentid) {
		SqlSession session = threadLocal.get();
		if (session == null) {
			session = getSessionFactory.get(environmentid).openSession();
			threadLocal.set(session);
			return session;
		}
		return session;
	}
	public static void closeSession() {
		SqlSession session = threadLocal.get();
		if (session != null) {
			threadLocal.set(null);
			session.close();
		}
	}
}

调用的时候

SessionFactory.setDbname("development");
SessionFactory.closeDbname();
举报
顶部