maven整合hibernate注意事项或易错点

本文介绍了在Eclipse中使用Maven整合Hibernate时可能会遇到的路径问题和主键生成策略问题。包括hibernate.properties文件的位置、hibernate.cfg.xml的放置路径、映射文件User.hbm.xml的配置以及hibernate.cfg.xml中包名的正确写法。同时提到了主键不是常规的"id"字段时如何处理,以及配置错误可能导致的MappingException。

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

本项目是在eclipse中完成,IDEA一样

一:路径问题(如图):

解释:

1.创建一个空的hibernate.properties文件并且放在src/main/resources下,否则程序提示,但不影响程序正常运行:
12:14:29.207 [main] INFO org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found

2. hibernate.cfg.xml文件一定要放在src/main/resources下,不能放在src/main/resources/config下,否则程序运行终止:
12:12:46.456 [main] INFO org.hibernate.cfg.Environment - HHH000205: Loaded properties from resource hibernate.properties: {hibernate.bytecode.use_reflection_optimizer=false}

3.映射文件User.hbm.xml里面的

<hibernate-mapping><!--  package="com.text" -->
	<!-- name:即实体类的全名 table:映射到数据库里面的那个表的名称 catalog:数据库的名称 -->
    <!-- name一定要包含包名,如果是name="User"则错误-->
	<class name="com.wordpython.domain.User" table="users" catalog="wordpython_ssm">

否则程序运行终止:

12:16:22.202 [main] DEBUG org.hibernate.boot.model.source.internal.hbm.ModelBinder - Mapping class: User -> users

4.hibernate.cfg.xml文件里包名一定是“/”并且一定要包含包名,否则程序运行终止::

<!-- 配置hibernate的映射文件(JaveBean与表的映射文件)所在的位置 -->
<mapping resource="com/wordpython/domain/User.hbm.xml" />

12:24:19.003 [main] INFO org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
二.主键生成策略问题:

1.数据库表中主键并非是id,比如我的主键是username,下面直接丢出完整的User.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">
<hibernate-mapping><!--  package="com.text" -->
	<!-- name:即实体类的全名 table:映射到数据库里面的那个表的名称 catalog:数据库的名称 -->
	<class name="com.wordpython.domain.User" table="users" catalog="wordpython_ssm">
		<!-- class下必须要有一个id的子元素 -->
		<!-- id是用于描述主键的 
			generator 表示主键生成策略  
			native 表示按照数据库中来设置(如果是mysql数据库,id会自动增长 ) 
			assigned 表示可以输入的 
			uuid  表示随机生成18的一个数做为ID-->
		<!-- 
		<id name="id" column="id">
			<generator class="native"></generator>
		</id> -->
		<id name="username" column="username">
			<generator class="assigned"></generator>
		</id>
		<!-- 使用property来描述属性与字段的对应关系 
			如果模型的属性 -->
		<property name="account"></property>
		<property name="password"></property>
		<property name="phone"></property>
	</class>
</hibernate-mapping>

2.assigned写错成 “assign”

<generator class="assign"></generator>

报错:org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.wordpython.domain.User]

 

完整项目含依赖可到https://github.com/wordpython/Maven_hibernate

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值