我有通過JNDI數據源連接到數據庫的hibernate。使用JNDI註冊MySQL數據源進行休眠
我的目的:使用JNDI的註冊表數據源來測試DAO層。
例
休眠配置
<hibernate-configuration>
<session-factory name="MySessionFactory">
<property name="hibernate.connection.datasource">java:jdbc/MysqlMyDS</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- mappings .... ->
</hibernate-configuration>
在測試類獲取會話工廠:
Configuration cgf = new Configuration().configure("/META-INF/hibernate.cfg.xml");
SessionFactory iceleadsSessionFactory = cgf.buildSessionFactory();
其結果:
16:04:37,753 ERROR DatasourceConnectionProvider:78 - Could not find datasource: java:jdbc/MysqlIceleadsDS
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
要註冊JNOI我使用示例(http://www.roseindia.net/tutorial/java/jdbc/registeringthedatasourcewithjndi.html)
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.ConnectionPoolDataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class RegisteringJNDIWithDataSource {
private static void startRegistry() throws RemoteException {
System.out.println(LocateRegistry.getRegistry());
LocateRegistry.createRegistry(1059);
System.out.println("RMI registry Stared.");
}
private static InitialContext createInitialContextContext()
throws NamingException {
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.rmi.registry.RegistryContextFactory");
properties.put(Context.PROVIDER_URL, "rmi://localhost:1059");
InitialContext initialContextcontext = new InitialContext(properties);
return initialContextcontext;
}
public static void main(String args[]) {
try {
startRegistry();
ConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("root");
((MysqlDataSource) dataSource).setServerName("192.168.10.13");
((MysqlDataSource) dataSource).setPort(3306);
((MysqlDataSource) dataSource).setDatabaseName("student");
InitialContext context = createInitialContextContext();
context.rebind("Source", dataSource);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
請建議解決方案。謝謝!
你爲什麼不改變'dataSource'爲'MysqlDataSource'的類型?那麼你可以擺脫這5個陣容。 – 2013-05-07 13:09:48
我試圖使用DataSource(而不是MysqlDataSource),但結果相同。 hibernate無法找到任何數據源的問題 – Tioma 2013-05-07 13:27:33
您是否爲測試環境設置了'jndi.properties'? http://docs.oracle.com/javase/jndi/tutorial/beyond/env/source.html – user1516873 2013-05-07 13:42:56