hibernate框架自动创建数据库表格

本文介绍Hibernate框架的基本配置方法,包括配置文件的修改、实体类的创建及DAO操作类的实现,并提供了一个简单的查询实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.修改hibernate.cfg.xml配置文件

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://127.0.0.1:6789/ucm
</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">SQLNAME</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
<!-- 添加自动创建数据库表格的配置 -->
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="com/cimstech/test/Teams.hbm.xml" />

</session-factory>

</hibernate-configuration>

2.修改Teams.hbm.xml数据库表映射配置文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->

 <!--添加所要创建的数据库表格的映射配置 --> 
<hibernate-mapping>
    <class name="com.cimstech.test.Teams" table="teams" catalog="ucm">
        <composite-id name="id" class="com.cimstech.test.TeamsId">
            <key-property name="player" type="java.lang.String">
                <column name="player" length="10" />
            </key-property>
            <key-property name="team" type="java.lang.String">
                <column name="team" length="9" />
            </key-property>
        </composite-id>
    </class>    

</hibernate-mapping>

3.创建实体Bean(映射类)

(1)Teams 类

package com.cimstech.test;


public class Teams implements java.io.Serializable {


// Fields


private TeamsId id;
// Constructors


/** default constructor */
public Teams() {
}


/** full constructor */
public Teams(TeamsId id) {
this.id = id;
}


// Property accessors


public TeamsId getId() {
return this.id;
}


public void setId(TeamsId id) {
this.id = id;
}


}


(2)TeamsId 类

package com.cimstech.test;


public class TeamsId implements java.io.Serializable {


// Fields


private String player;
private String team;


// Constructors


/** default constructor */
public TeamsId() {
}


/** full constructor */
public TeamsId(String player, String team) {
this.player = player;
this.team = team;
}


// Property accessors


public String getPlayer() {
return this.player;
}


public void setPlayer(String player) {
this.player = player;
}


public String getTeam() {
return this.team;
}


public void setTeam(String team) {
this.team = team;
}


public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof TeamsId))
return false;
TeamsId castOther = (TeamsId) other;


return ((this.getPlayer() == castOther.getPlayer()) || (this
.getPlayer() != null && castOther.getPlayer() != null && this
.getPlayer().equals(castOther.getPlayer())))
&& ((this.getTeam() == castOther.getTeam()) || (this.getTeam() != null
&& castOther.getTeam() != null && this.getTeam()
.equals(castOther.getTeam())));
}


public int hashCode() {
int result = 17;


result = 37 * result
+ (getPlayer() == null ? 0 : this.getPlayer().hashCode());
result = 37 * result
+ (getTeam() == null ? 0 : this.getTeam().hashCode());
return result;
}


}


(3)TeamsDAO


package com.cimstech.test;

import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TeamsDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(TeamsDAO.class);


// property constants


public void save(Teams transientInstance) {
log.debug("saving Teams instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}


public void delete(Teams persistentInstance) {
log.debug("deleting Teams instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}


public Teams findById(com.cimstech.test.TeamsId id) {
log.debug("getting Teams instance with id: " + id);
try {
Teams instance = (Teams) getSession().get(
"com.cimstech.test.Teams", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}


public List findByExample(Teams instance) {
log.debug("finding Teams instance by example");
try {
List results = getSession()
.createCriteria("com.cimstech.test.Teams")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}


public List findByProperty(String propertyName, Object value) {
log.debug("finding Teams instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Teams as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}


public List findAll() {
log.debug("finding all Teams instances");
try {
String queryString = "from Teams";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}


public Teams merge(Teams detachedInstance) {
log.debug("merging Teams instance");
try {
Teams result = (Teams) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}


public void attachDirty(Teams instance) {
log.debug("attaching dirty Teams instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}


public void attachClean(Teams instance) {
log.debug("attaching clean Teams instance");
try {
getSession().buildLockRequest(LockOptions.NONE).lock(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}

4.执行一个查询数据的操作即可

public void test2() throws Exception 
{
try
{

Session session = HibernateSessionFactory.getSession();

String sql = "select * from Teams";
List list = session.createSQLQuery(sql).
addScalar("team", StandardBasicTypes.STRING)
.addScalar("player",StandardBasicTypes.STRING).list();
Iterator iter = list.iterator();
while(iter.hasNext())
{
Object[] objs =(Object[])iter.next();
System.out.println("team="+objs[0]);
System.out.println("player="+objs[1]);
System.out.println("--------------------------");
}
}
catch(Exception e)
{
throw e;
}
}

### Spring Boot 中使用 Hibernate 连接 MySQL 数据库配置教程 在 Spring Boot 应用程序中集成 Hibernate 和 MySQL 是一种常见的开发需求。以下是详细的配置方法以及示例代码。 #### 1. 配置 `application.properties` 文件 为了使应用程序能够成功连接到 MySQL 数据库,需要正确设置 `application.properties` 文件中的属性。以下是一个典型的配置: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect ``` 上述配置指定了数据库 URL、用户名、密码以及其他必要的参数[^1]。其中: - `spring.datasource.url`: 数据库的位置及其附加选项。 - `spring.jpa.hibernate.ddl-auto=update`: 自动更新结构以匹配实体类定义。 - `spring.jpa.show-sql=true`: 启用 SQL 查询日志记录以便调试。 #### 2. 添加依赖项至 Gradle 或 Maven 构文件 确保项目构工具(Gradle 或 Maven)已包含所需的依赖项来支持 MySQL 和 Hibernate 功能。 对于 **Gradle** 用户,在 `build.gradle` 文件中添加如下内容: ```gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'mysql:mysql-connector-java' } ``` 而对于 **Maven** 用户,则需修改 `pom.xml` 如下所示: ```xml <dependencies> <!-- JPA and Database --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> ``` 这些依赖分别引入了用于操作关系型数据的支持包和具体的 MySQL JDBC 驱动器[^2]。 #### 3. 创建实体类 (Entity Class) 创建一个 Java 类示要映射的数据库。例如,假设有一个名为 `User` 的表格存储用户信息: ```java package com.example.mysql_testing.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; // Getters & Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 此段代码展示了如何通过注解方式声明字段与列之间的对应关系,并利用自增主键机制生成唯一 ID 值[^3]。 #### 4. 编写 Repository 接口 接着定义一个接口继承自 `JpaRepository<T, ID>` 来获取基本 CRUD 方法的功能而无需额外编码: ```java package com.example.mysql_testing.repository; import com.example.mysql_testing.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> {} ``` 这样就可以轻松调用保存、删除或者查询对象的方法了。 #### 5. 测试服务层逻辑 最后可以在控制器或其他组件里注入该仓库实例并执行业务处理流程测试其功能正常与否。 --- ### 总结 以上就是关于如何在 Spring Boot 中应用 Hibernate 实现对接 MySQL 数据库的一个完整过程介绍。它涵盖了从基础环境搭直至高级特性使用的各个方面知识点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值