简体   繁体   中英

Hibernate: Set a default in many-to-one class mapping

I am trying to map a class Language to a class User.

Many to one mapping is working fine, and through the functionality of the app I can set the value from it's default of null to a particular value.

The problem is that I'd like to set the default mapping to idLanguage 1, but when it maps everything is set to null.

I have tried:

< many-to-one name="language" class="com. \etc\ .language.Language" column="language" default="1" lazy="false" />

However that gives me an error "Attribute default must be declared for element type Many To One.

What to do?

(note: language is mapped to language object in user class, rather than a language id. Setting in the app puts the id of the language in the language column, replacing null value)

I hope the languages will be seed data in your application. Then have a separate field in the User mapping and set it to 1. The Object mapping can be used while loading the User bean.So modify the mapping as below. 字段并将其设置为1。可以在加载User Bean时使用Object映射。因此,请如下修改映射。

< many-to-one name="language" class="com. \etc\ .language.Language" column="language" lazy="false" insert="false" update="false"/>

<property name="langId" column="language"/>

This way it will be more performative as you don't have to fetch the Languages bean from the DB before you save the User bean. Also on load of User the languages will be available to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM