如果设置正确,您的代码将起作用
jndi.properties。该文件应位于类路径中。
这是工作示例:
服务器:
public static void main(String[] args) throws Exception{ LocateRegistry.createRegistry(1099); ConnectionPoolDataSource dataSource = createDataSource("root", ""); InitialContext context = createContext(); context.bind("MysqlMyDS", dataSource); System.out.println("context created!"); } private static InitialContext createContext() throws NamingException { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); env.put(Context.PROVIDER_URL, "rmi://localhost:1099"); InitialContext context = new InitialContext(env); return context; } private static ConnectionPoolDataSource createDataSource(String username, String password) { MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource(); dataSource.setUser(username); dataSource.setPassword(password); dataSource.setServerName("localhost"); dataSource.setPort(3306); dataSource.setDatabaseName("test"); return dataSource; }客户:
hibernate.cfg.xml注意:数据源jndi名称应与您设置的名称完全相同
context.bind()
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory> <property name="hibernate.connection.datasource">MysqlMyDS</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property></session-factory></hibernate-configuration>
jndi.properties(如果需要,可以在代码中或使用-D选项进行设置)
java.naming.factory.initial=com.sun.jndi.rmi.registry.RegistryContextFactoryjava.naming.provider.url=rmi://localhost:1099
单元测试
public class TestClient { @Test public void testCfg() throws Exception { Configuration cgf = new Configuration().configure("/hibernate.cfg.xml"); cgf.buildSessionFactory(); }}


