To connect to DB using Hibernate users have to make the next steps:
Let’s do it step by step:
1. Create environment with a database server (MySQL in our case):
2. Create a new user in a database:How to create a new user – click here.
Database name : cirrusgridDb Username : cirrusgrid Password : cirrusgrid
For this example we’ve created table books with fields book_name and book_author inside the cirrusgridDb database.
3. Modify the following configuration files of your web-application: hibernate.cfg.xml
<hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://mysql{node_id}.{your_env_name}.qloud.asia:3306/cirrusgridDb</property> <property name="hibernate.connection.username">cirrusgrid</property> <property name="hibernate.connection.password">cirrusgrid</property> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="com/Testdata.hbm.xml"/> </session-factory> </hibernate-configuration>
Tip: Don’t miss to put the correct values to the hibernate.connection.url string instead of the text inside curly brackets. jdbc:mysql://mysql{node_id}.{your_env_name}.qloud.asia:3306/cirrusgridDb where {node_id} - ID of the container with MySQL server you want to receive the access to. It can be seen at the dashboard:
hibernate.revenge.xml
<hibernate-reverse-engineering> <schema-selection match-catalog="cirrusgridDb"/> <table-filter match-name="books"/> </hibernate-reverse-engineering>
For the next step we’ve used reverse engineering mechanism and got 2 files in our web-project:
4. Create a simple Java method, which will add a new row to the books table in our database:
public void addBook(){ Session s = HibernateUtil.getSessionFactory().getCurrentSession(); s.beginTransaction(); Books book = new Books("romeo and juliet","william shakespeare "); s.save(book); s.getTransaction().commit(); }
Note that you have to put the connector for database (.jar library) to your project or to the appropriate web-server’s folder in the environment.
Powered by BetterDocs
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.