栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用JNDI为Hibernate注册MySQL数据源

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用JNDI为Hibernate注册MySQL数据源

如果设置正确,您的代码将起作用

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();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/388169.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号