在hibernate中插入用户时如何创建新数据库

时间:2018-05-18 05:12:34

标签: java mysql database hibernate hql

问题陈述: 我正在尝试在用户注册时创建数据库。

当我使用

String s="create database " + userVo.getUserdbname()+";";
session.createSQLQuery(s).executeUpdate();

它工作正常但是当我使用Dao代码中显示的 createDatabase(String s)方法时,即使我为配置设置新属性,也不会创建新数据库。

Dao代码插入用户并以用户注册的方式创建数据库。



package com.dao;

import com.vo.UserVo;
import java.util.List;
import java.util.Properties;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
//import org.hibernate.cfg.Environment;
//import org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider;

public class UserDao {

    Configuration cfg;
    SessionFactory factory;
    Session session;
    Transaction t;

    void dbConnection() {
        cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        factory = cfg.buildSessionFactory();
        session = factory.openSession();

    }

    public void insertUser(UserVo userVo) {
        dbConnection();
        t = session.beginTransaction();
        session.save(userVo);
//        String s="create database " + userVo.getUserdbname()+";";
//        System.out.println(s);
//        session.createSQLQuery(s).executeUpdate();
        t.commit();
        session.close();
        factory.close();
        createdatabase(userVo.getUserdbname());
        System.out.println("inserted");
    }

//    public int dbUserId() {
//    }
    public List viewUser() {
        dbConnection();
        Query q;
        q = session.createQuery("from UserVo");
        return q.list();
    }

    private void createdatabase(String userdbname) {
        try {
            System.out.println("DB................" + userdbname);
            Configuration configuration = new Configuration();
            Properties properties = new Properties();
            properties.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
            properties.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/" + userdbname + "?createDatabaseIfNotExist=true");
            properties.setProperty("hibernate.connection.username", "root");
            properties.setProperty("connection.password", "");
            properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            properties.setProperty("connection.pool_size", "11");
            properties.setProperty("show_sql", "true");
            properties.setProperty("hbm2ddl.auto", "update");
//        configuration.setProperties(properties);
//        configuration.setProperty("packagesToScan", "com.my.app");
//        properties.put(Environment.CONNECTION_PROVIDER, InjectedDataSourceConnectionProvider.class.getName());
//        cfg.addProperties(properties);
            SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
            session = sessionFactory.openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Query q;
//        session.createQuery("create database " + userVo.getUserdbname());
    }

}




Hibernet.cfg.xml



<?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.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/global_db?createDatabaseIfNotExist=true</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">11</property>
        <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="com.vo.UserVo"/>
    </session-factory>
</hibernate-configuration>
&#13;
&#13;
&#13;

UserController中

&#13;
&#13;
package com.controller;

import com.dao.UserDao;
import com.vo.UserVo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String flag = request.getParameter("flag");
        if (flag.equals("insertuser")) {
            insertuser(request, response);
        } else if (flag.equals("userlogin")) {
            userlogin(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    private void insertuser(HttpServletRequest request, HttpServletResponse response) {
        UserVo userVo = new UserVo();
        UserDao userdao = new UserDao();
        userVo.setUsername(request.getParameter("user_name"));
        userVo.setLastname(request.getParameter("user_last_name"));
        userVo.setFirstname(request.getParameter("user_first_name"));
        userVo.setUseremail(request.getParameter("user_email"));
        userVo.setUserpassword(request.getParameter("user_password"));
        userVo.setStatus(1);
        userVo.setUserdbname((userdao.viewUser().size() + 1) + "_" + userVo.getFirstname() + "_" + userVo.getLastname() + "_front");
        System.out.println(userVo.getUserdbname());
        userdao.insertUser(userVo);
    }

    private void userlogin(HttpServletRequest request, HttpServletResponse response) {

    }

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我得到了解决方案

我首先为数据库创建创建两个 Cfg 文件 主数据库的 hibernate.cfg.xml 和新用户数据库创建的第二个文件 user.cfg.xml ,您可以在下面的代码中看到它。

user.cfg.xml

<?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.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url"></property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">11</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

userDbConnection()方法:

    public void userDbconnection(String dbname) {
        conf = new Configuration().configure("user.cfg.xml");
        conf.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/" + dbname + "?createDatabaseIfNotExist=true");
        conf.addAnnotatedClass(TrainingUserVo.class);
        sessionFactory = conf.buildSessionFactory();
        s = sessionFactory.openSession();
    }

当我调用该方法时,它将创建数据库如果不存在并建立与该数据库的连接,因为正常 hibernate.cfg.xml 文件适用于数据库。 / p>