01: /*
02: * JFox - The most lightweight Java EE Application Server!
03: * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
04: *
05: * JFox is licenced and re-distributable under GNU LGPL.
06: */
07: package org.jfox.entity;
08:
09: import java.sql.Connection;
10: import java.sql.SQLException;
11: import javax.persistence.EntityTransaction;
12: import javax.persistence.Query;
13: import javax.sql.DataSource;
14:
15: import org.jfox.ejb3.transaction.TxConnectionsThreadLocal;
16:
17: /**
18: * Persistence Manager, 创建和管� datasource, query template
19: *
20: * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
21: */
22: public class EntityManagerImpl extends EntityManagerExt {
23:
24: // private static final Logger logger = Logger.getLogger(EntityManagerImpl.class);
25:
26: private EntityManagerFactoryImpl emFactory = null;
27:
28: public EntityManagerImpl(EntityManagerFactoryImpl emFactory) {
29: this .emFactory = emFactory;
30: }
31:
32: protected DataSource getDataSource() {
33: return emFactory.getDataSource();
34: }
35:
36: public String getUnitName() {
37: return emFactory.getUnitName();
38: }
39:
40: public Connection getConnection() throws SQLException {
41: //事务 commit 时 XAPool �会自动 close 连接,
42: //建立维护机制(TX Synchronization),在事务 commit 之�立�调用 connection.close,是 connection 回收到 Connection Pool
43: DataSource ds = getDataSource();
44: Connection conn = ds.getConnection();
45: // add to threadlocal, 以便commit时, Tx sync 能够释放 connection,
46: // 由 TransactionManager.begin时注册的 Synchronization 负责 release
47: if (getTransaction().isActive()) {
48: TxConnectionsThreadLocal.addConnection2Tx(conn);
49: }
50: return conn;
51: }
52:
53: public QueryExt createNamedQuery(String name) {
54: NamedSQLTemplate sqlTemplate = emFactory.getNamedQuery(name);
55: // 没有对应的 SQLTemplate
56: if (sqlTemplate == null) {
57: throw new NamedQueryNotFoundException(name);
58: }
59: // æ??供的å?‚æ•°ä¸?够,ä¸?能这么简å?•ï¼Œä¼ é€’çš„ä¼ è¾“å?¯èƒ½æ˜¯ä¸ªå¯¹è±¡
60: /*
61: if(sqlTemplate.getExpressions().length != args.length) {
62: throw new NamedQueryArgumentException("Need " + sqlTemplate.getExpressions().length + " arguments for NamedQuery " + name + ", you supplied " + args.length);
63: }
64: */
65: return new SQLQuery(this , sqlTemplate);
66: }
67:
68: // javax.persistence.EntityManager
69:
70: public Query createNativeQuery(String sqlString) {
71: return createNativeQuery(sqlString, MappedEntity.class);
72: }
73:
74: public Query createNativeQuery(String sqlString, Class resultClass) {
75: SQLTemplate sqlTemplate = new SQLTemplate(sqlString,
76: resultClass);
77: return new SQLQuery(this , sqlTemplate);
78: }
79:
80: public EntityTransaction getTransaction() {
81: return emFactory.getEntityManagerFactoryBuilder()
82: .getEntityTransaction();
83: }
84:
85: public void close() {
86:
87: }
88:
89: public static void main(String[] args) {
90:
91: }
92: }
|