导致混淆的休眠代码中的“ TM”

Edd*_*man 5 java hibernate

我正在学习本书Java Persistence with Hibernate,在PDF版本的第24页上有一个类似的声明:

UserTransaction tx = TM.getUserTransaction();
Run Code Online (Sandbox Code Playgroud)

我不知道从哪里来TM。我已经搜索了一段时间,但找不到任何答案。因此,我无法在Netbeans中运行我的代码。

我还可以JPA在代码的某处看到。这还意味着什么?

感谢您的帮助

整个代码是:

public class HelloWorldJPA {

    public static void main(String[] args){
        try {
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloWorldPU");

            UserTransaction tx = TM.getUserTransaction();
            try {
                tx.begin();
            } catch (NotSupportedException | SystemException ex) {
                Logger.getLogger(HelloWorldJPA.class.getName()).log(Level.SEVERE, null, ex);
            }

            EntityManager em = emf.createEntityManager();

            Message message = new Message();
            message.setText("Hello World!");

            em.persist(message);

            tx.commit();

            em.close();
        } catch (HeuristicMixedException | HeuristicRollbackException | IllegalStateException | RollbackException | SecurityException | SystemException ex) {
            Logger.getLogger(HelloWorldJPA.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*K S 7

您问题的确切解决方案

  1. TM 绝对是一个实例变量,通常为每个测试套件设置单个数据库连接管理器

  2. 请从此链接下载本书源代码

  3. 查找 TransactionManagerTest.java 类

公共类 TransactionManagerTest {

// Static single database connection manager per test suite
static public TransactionManagerSetup TM;

@Parameters({"database", "connectionURL"})
@BeforeSuite()
public void beforeSuite(@Optional String database,
                        @Optional String connectionURL) throws Exception {
    TM = new TransactionManagerSetup(
        database != null
            ? DatabaseProduct.valueOf(database.toUpperCase(Locale.US))
            : DatabaseProduct.H2,
        connectionURL
    );
}

@AfterSuite(alwaysRun = true)
public void afterSuite() throws Exception {
    if (TM != null)
        TM.stop();
}
Run Code Online (Sandbox Code Playgroud)

}

你会得到答案:-)

  1. 我总是建议从 manning 发布站点在线获取源代码,以便更好地实际理解。他们还在他们的官方网站上上传了与当前上下文相关的源代码。