我使用靜態的前綴值作為DEPT,我不能根據我的dept屬性的值來改變它,但我想在id生成時根據dept的值動態地添加前綴。
@GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "DEPT"), strategy = "com.otomate.registerservice.service.IdGenerator")
我的UserModel類
import javax.persistence.Column。
import javax.persistence.Entity。
import javax.persistence.GeneratedValue;
import javax.persistence.Id。
import javax.persistence.Table。
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import lombok.Data。
import lombok.Getter;
IDGenerator類
public class IdGenerator implements IdentifierGenerator, 可配置的 {
private String prefix;
public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
String query = String.format("select %s from %s"/span>,
session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName()。
obj.getClass().getSimpleName())。
Stream<String> ids = session.createQuery(query).stream()。
Long max = ids.map(o -> o.replace(prefix "-", ")
.mapToLong(Long::parseLong)
.max()
.orElse(0L)。
return prefix "-" (max 1)。
}
public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
prefix = properties.getProperty("prefix")。
}
}
我的輸入:
{
"firstName":"Dhamodaran"。
"lastName":"N",
"dept":"SALES",
" password":"12345678",
"email":"[email protected]",
"電話":"1379143242"。
"角色":"USER"。
}
它是"部門"。"SALES"所以我希望我的ID像SALES-1但我目前得到的是DEPT-1所以請幫助我用一些基于當前輸入的動態ID來修復它。 謝謝大家的幫助。
uj5u.com熱心網友回復:
你可以同意這樣的規則:前綴不是前綴值,而是要從中讀取值的屬性名稱。
因此,你可以做類似于以下的事情:
final String prefixValue = BeanUtils. getProperty(obj, prefix)。
String query = String.format("select %s from %s"/span>,
session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName()。
obj.getClass().getSimpleName())。
Stream<String> ids = session.createQuery(query).stream()。
Long max = ids
.filter( o -> o.startWith(prefixValue))
.map(o -> o.replace(prefixValue "-"/span>, ""/span>)
.mapToLong(Long::parseLong)
.max()
.orElse(0L)。
return prefixValue "-" (max 1)。
但是,當你有大量的資料時,請考慮其效率:)你要不斷地獲取所有物體的身份,這并不好。
uj5u.com熱心網友回復:
所以你希望前綴取自你所存盤的UserModel實體的dept欄位,對嗎?
在這種情況下,你需要把這個添加到你的生成方法中,例如:
public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
String query = String.format("select %s from %s"/span>,
session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName()。
obj.getClass().getSimpleName())。
Stream<String> ids = session.createQuery(query).stream()。
Long max = ids.map(o -> o.replace(prefix "-", ")
.mapToLong(Long::parseLong)
.max()
.orElse(0L)。
String idPrefix = prefix。
if(obj instanceof UserModel) {
UserModel user = (UserModel) obj;
if(user.getDept() != null && !user.getDept().trim().isEmpty() ) {
idPrefix = user.getDept().trim()。
}
}
return idPrefix "-" (max 1)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/309846.html
標籤:
