How does hibernate connect to mysql database?
Teach you how to connect hibernate to mysql database. As long as you follow my steps below, there will be absolutely no problem. The code can be used directly or copied.
#1. First, we connect hibernate to the most basic database using mysql. See a java project and a package named book. Add a java class Book.java under the book package. The code is as follows:
package book; public class Book { private Integer id; private String name; private String writer; public Integer get hibernate
The most basic database connection , using mysql. See a java project and a package named "book"
2. Then add a java class Book.java under the book package , the code is as follows:
package book; public class Book { private Integer id; private String name; private String writer; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } }
3. Then create a book.hbm.xml under the book package, its code As follows:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="book" default-lazy="false"> <class name="Book"> <id name="id"> <generator class="increment"/> </id> <property name="name" ></property> <property name="writer" ></property> </class> </hibernate-mapping>
4. This matter forms a mapping relationship with the field names in the database. Create the book table in mysql yourself. Correspondingly, the id is self-increasing. Then create a hibernate.cfg.xml in the root directory of the project. The code is as follows:
<?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="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/mydb</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <!-- <property name="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</property>--> <!-- <property name="current_session_context_class">thread</property>--> <mapping resource="book/Book.hbm.xml" /> </session-factory> </hibernate-configuration>
5. This is to connect to the mysql database. Change the username and password to your mysql database
<property name="show_sql">true</property>这是在后台打印sql语句 <mapping resource="book/Book.hbm.xml" />这是找到映射文件。
6. Then some test classes: the code is as follows:
package test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import book.Book; public class MainTest { /** * @param args */ public static void main(String[] args) { try { Configuration cfg=new Configuration()。configure(); SessionFactory sf=cfg.buildSessionFactory(); Session session = sf.openSession(); Transaction ts=session.beginTransaction(); Book b=new Book(); b.setName("hibernate"); b.setWriter("div"); session.save(b); // Book b=(Book) session.get(Book.class,1); // if(b!=null){ // b.setName("xujun"); // System.out.println("书名为:"+b.getName()); // System.out.println("作者为:"+b.getWriter()); // session.delete(b); // } ts.commit(); session.close(); sf.close(); } catch (Exception e) { e.printStackTrace(); } } }
7. The fields of the mysql table are as follows :
8. After the database is built, you can test it. By the way, the key thing hasn’t been mentioned yet, we have to add antlr.jar, cglib.jar, asm.jar, asm-attrs.jar, commons-colletions.jar, commons-logging.jar, ehcache.jar, jta.jar, dom4.jar, log4.jar, hibernate3.jar are introduced into the lib directory
The above is the detailed content of How does hibernate connect to mysql database?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())
