[RESOLVIDO]Mapeamento HIbernate

11 respostas
B

Bom dia!

Estou tentando fazer o seguinte mapemamento:

Tenho uma classe Usuario e outra classe Fraud.

Preciso ter o relacionamento 2 para n .

Estou fazendo assim:

Classe Users

@OneToMany(mappedBy="usersRigged",cascade=CascadeType.PERSIST,fetch=FetchType.LAZY)	
	private Set<Fraud> riggedFrauds = new HashSet<Fraud>();	
	
	@OneToMany(mappedBy="usersFraudster",cascade=CascadeType.PERSIST,fetch=FetchType.LAZY)	
	private Set<Fraud> fraudsterFrauds = new HashSet<Fraud>();

Classe Fraud

@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "fraudsterIdentity",unique=true,nullable=false)  
	@ForeignKey(inverseName="identity",name="fraudsterIdentity")
	private Users usersFraudster;
	
	@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "riggedIdentity",unique=false,nullable=false)  
	@ForeignKey(inverseName="identity",name="riggedIdentity")
	private Users usersRigged;

E gera o seguinte erro:

05/04/2010 11:42:37 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
SEVERE: Unsuccessful: alter table fraudesshml.fraud add index fraudsterIdentity (fraudsterIdentity), add constraint fraudsterIdentity foreign key (fraudsterIdentity) references fraudesshml.users (identity)
05/04/2010 11:42:37 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
SEVERE: Duplicate key name 'fraudsterIdentity'
05/04/2010 11:42:39 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: schema update complete

Alguem sabe oq esta de errado???

11 Respostas

B

Alguma opnião?

Obrigado

R

Mostra as suas duas entidades inteiras

B

Ai vai:

Users:

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.ForeignKey;
import org.hibernate.validator.NotNull;


@Entity
@Table(name="users")
public class Users implements br.com.conrado.j4b.domain.Entity {

	private static final long serialVersionUID = 3282330527791510026L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)  
	@Column(name="identity")
	private Long identity;	
	
	@NotNull
	@Column(name="custId", length=15, nullable=false, unique=false)
	private Integer custId;
	
	@NotNull
	@Column(name="nickName", length=50, nullable=false, unique=false)
	private String nickName;
	
	@NotNull
	@Column(name="name", length=50, nullable=false, unique=false)
	private String name;
	
	@NotNull
	@Column(name="apelido", length=50, nullable=false, unique=false)
	private String apelido;
	
	@NotNull
	@Column(name="email", length=100, nullable=false, unique=false)
	private String email;
	
	/**
	 * Sigla:
	 * F ? CPF
	 * J - CNPJ
	 */
	@Column(name="documentType", length=1, nullable=true, unique=false)
	private String documentType;	
	
	@Column(name="documentNumber", length=15)
	private Double documentNumber;
	
	@NotNull
	@Column(name="password", length=24, nullable=false, unique=false)
	private String password;
	
	@Column(name="adress", length=100, unique=false)
	private String adress;
	
	@Column(name="adress2", length=100, unique=false)
	private String adress2;
	
	@Column(name="zipCode", length=8, unique=false)
	private Integer zipCode;
	
	@Column(name="city", length=25, unique=false)
	private String city;
	
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name="birthDate")
	private Date birthDate;
	
	
	@Column(name="cityCode",length=8)
	private Integer cityCode;
	
	@Column(name="telephoneNumber",length=8)
	private Integer telephoneNumber;
	
	@Column(name="telephoneNumber2",length=8)
	private Integer telephoneNumber2;
	
	@Column(name="currimentScore",length=6)
	private Integer currimentScore;

	@Column(name="negativeScore",length=6)
	private Integer negativeScore;
	
	@Column(name="positiveScore",length=6)
	private Integer positiveScore;
	
	@Column(name="scoreInOffer",length=6)
	private Integer scoreInOffer;
	
	@Column(name="hasChangeDateInSevenDays")
	private Boolean hasChangeDateInSevenDays;		
	
	@OneToMany(mappedBy="usersRigged",cascade=CascadeType.PERSIST,fetch=FetchType.LAZY)	
	private Set<Fraud> riggedFrauds = new HashSet<Fraud>();	
	
	@OneToMany(mappedBy="usersFraudster",cascade=CascadeType.PERSIST,fetch=FetchType.LAZY)	
	private Set<Fraud> fraudsterFrauds = new HashSet<Fraud>();
	
	@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "userStateIdentity")  
	@ForeignKey(inverseName="identity",name="userStateIdentity")
	private State state;
	
	@ManyToMany(fetch = FetchType.LAZY,cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH})  
	@JoinTable(
		name = "userAccessIdentification", 				
		joinColumns = { 
			@JoinColumn(
						name = "userIdentity",
						nullable = false, 
						insertable=true,
						updatable =  false) }, 
		inverseJoinColumns = {  
			@JoinColumn(
						name = "accessIdentificationIdentity", 
						nullable = false, 
						insertable=true,
						updatable = false) }
	)  	
	Set<AccessIdentification> accessIdentifications = new HashSet<AccessIdentification>();
	
		
	public Long getIdentity() {
		return identity;
	}

	public void setIdentity(Long identity) {
		this.identity = identity;
	}

	public Integer getCustId() {
		return custId;
	}

	public void setCustId(Integer custId) {
		this.custId = custId;
	}

	public String getNickName() {		
		return nickName;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getApelido() {
		return apelido;
	}

	public void setApelido(String apelido) {
		this.apelido = apelido;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getDocumentType() {
		return documentType;
	}

	public void setDocumentType(String documentType) {
		this.documentType = documentType;
	}

	public Double getDocumentNumber() {
		return documentNumber;
	}

	public void setDocumentNumber(Double documentNumber) {
		this.documentNumber = documentNumber;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAdress() {
		return adress;
	}

	public void setAdress(String adress) {
		this.adress = adress;
	}

	public String getAdress2() {
		return adress2;
	}

	public void setAdress2(String adress2) {
		this.adress2 = adress2;
	}

	public Integer getZipCode() {
		return zipCode;
	}

	public void setZipCode(Integer zipCode) {
		this.zipCode = zipCode;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public Date getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	public Integer getCityCode() {
		return cityCode;
	}

	public void setCityCode(Integer cityCode) {
		this.cityCode = cityCode;
	}

	public Integer getTelephoneNumber() {
		return telephoneNumber;
	}

	public void setTelephoneNumber(Integer telephoneNumber) {
		this.telephoneNumber = telephoneNumber;
	}

	public Integer getTelephoneNumber2() {
		return telephoneNumber2;
	}

	public void setTelephoneNumber2(Integer telephoneNumber2) {
		this.telephoneNumber2 = telephoneNumber2;
	}

	public Integer getCurrimentScore() {
		return currimentScore;
	}

	public void setCurrimentScore(Integer currimentScore) {
		this.currimentScore = currimentScore;
	}

	public Integer getNegativeScore() {
		return negativeScore;
	}

	public void setNegativeScore(Integer negativeScore) {
		this.negativeScore = negativeScore;
	}

	public Integer getPositiveScore() {
		return positiveScore;
	}

	public void setPositiveScore(Integer positiveScore) {
		this.positiveScore = positiveScore;
	}

	public Integer getScoreInOffer() {
		return scoreInOffer;
	}

	public void setScoreInOffer(Integer scoreInOffer) {
		this.scoreInOffer = scoreInOffer;
	}

	public Boolean getHasChangeDateInSevenDays() {
		return hasChangeDateInSevenDays;
	}

	public void setHasChangeDateInSevenDays(Boolean hasChangeDateInSevenDays) {
		this.hasChangeDateInSevenDays = hasChangeDateInSevenDays;
	}	

	public Set<Fraud> getRiggedFrauds() {
		return riggedFrauds;
	}

	public void setRiggedFrauds(Set<Fraud> riggedFrauds) {
		this.riggedFrauds = riggedFrauds;
	}

	public void addRiggedFrauds(Fraud frauds) {
		this.riggedFrauds.add(frauds);
	}

	public void removeRiggedFrauds(Fraud frauds) {
		this.riggedFrauds.remove(frauds);
	}	
	
	public Set<Fraud> getFraudsterFrauds() {
		return fraudsterFrauds;
	}

	public void setFraudsterFrauds(Set<Fraud> fraudsterFrauds) {
		this.fraudsterFrauds = fraudsterFrauds;
	}

	public void addFraudsterFrauds(Fraud frauds) {
		this.fraudsterFrauds.add(frauds);
	}

	public void removeFraudsterFrauds(Fraud frauds) {
		this.fraudsterFrauds.remove(frauds);
	}	
	
	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

	public Set<AccessIdentification> getAccessIdentifications() {
		return accessIdentifications;
	}

	public void setAccessIdentifications(
			Set<AccessIdentification> accessIdentifications) {
		this.accessIdentifications = accessIdentifications;
	}
	
	public void addAccessIdentification(AccessIdentification accessIdentification) {
		this.accessIdentifications.add(accessIdentification);
	}

	public void removeAccessIdentification(AccessIdentification accessIdentification) {
		this.accessIdentifications.remove(accessIdentification);
	}
	
	
	
	@Override
	public int hashCode() {
		return  this.identity == null ? 1 : this.identity.hashCode();	
	}
	
	@Override
	public boolean equals(Object obj) {		
		return obj instanceof Users && this.equals((Users)obj);
	}	
	
	private boolean equals(Users other) {		
		return this.identity != null && 
				this.identity.equals(other.identity);
	}

}

Fraud:

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.Type;
import org.hibernate.validator.NotNull;

@Entity
@Table(name="fraud")
public class Fraud implements br.com.conrado.j4b.domain.Entity { 

	private static final long serialVersionUID = -9204002124410616720L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)  
	@Column(name="identity")
	private Long identity;
	
	@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "responsibleIdentity")  
	@ForeignKey(inverseName="identity",name="responsibleIdentity")
	private Responsible responsible;
	
	@NotNull
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="tkoIdentity") 
	@ForeignKey(inverseName="identity",name="tkoIdentity")
	private Tko tko;
	
	@NotNull
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="bofFtsIdentity") 
	@ForeignKey(inverseName="identity",name="bofFtsIdentity")
	private BofFts bofFts;
	
	@NotNull
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="datesIdentity") 
	@ForeignKey(inverseName="identity",name="datesIdentity")	
	private Dates dates;
	
	@NotNull
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="marketPayIdentity") 
	@ForeignKey(inverseName="identity",name="marketPayIdentity")	
	private MarketPay marketPay;
	
	@NotNull
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="bankInformationIdentity") 
	@ForeignKey(inverseName="identity",name="bankInformationIdentity")	
	private BankInformation bankInformation;
	
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="keyWordIdentity") 
	@ForeignKey(inverseName="identity",name="keyWordIdentity")		
	private KeyWord keyWord;		
	
	@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "riggedIdentity",unique=false,nullable=false)  
	@ForeignKey(inverseName="identity",name="riggedIdentity")
	private Users usersRigged;
	
	@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "fraudsterIdentity",unique=true,nullable=false)  
	@ForeignKey(inverseName="identity",name="fraudsterIdentity")
	private Users usersFraudster;
	
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="productIdentity") 
	@ForeignKey(inverseName="identity",name="productIdentity")		
	private Product product;	
	
	@NotNull
	@OneToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
	@JoinColumn(name="defectAnalysisIdentity") 
	@ForeignKey(inverseName="identity",name="defectAnalysisIdentity")	
	private DefectAnalysis defectAnalysis;
	
	
	@Column(name="logCase", nullable=false, unique=true,length=10)
	private Integer logCase;
	
	@Column(name="payId", nullable=false, unique=true, length=12)
	private Integer payId;
	
	@Column(name="statusFraud", nullable=false, unique=false, length=1)
	private String statusFraud;	
	
	@Column(name="typeFraud", nullable=false, unique=false, length=1)
	private String typeFraud;
	
	@Column(name="profileCase", nullable=false, unique=false, length=2)
	private String profileCase;
	
	@Column(name="othesComments", nullable=true, unique=false, length=250)
	private String othesComments;
	
	@Type(type="true_false")
	@Column(name="solicitationData")
	private Boolean solicitationData;
	
	@Type(type="true_false")
	@Column(name="buyerAnnounced")
	private Boolean buyerAnnounced;
	
	@Type(type="true_false")
	@Column(name="sendData")
	private Boolean sendData;
	

	public Long getIdentity() {
		return identity;
	}

	public void setIdentity(Long identity) {
		this.identity = identity;
	}

	public Responsible getResponsible() {
		return responsible;
	}

	public void setResponsible(Responsible responsible) {
		this.responsible = responsible;
	}

	public Tko getTko() {
		return tko;
	}

	public void setTko(Tko tko) {
		this.tko = tko;
	}

	public BofFts getBofFts() {
		return bofFts;
	}

	public void setBofFts(BofFts bofFts) {
		this.bofFts = bofFts;
	}

	public Dates getDates() {
		return dates;
	}

	public void setDates(Dates dates) {
		this.dates = dates;
	}

	public MarketPay getMarketPay() {
		return marketPay;
	}

	public void setMarketPay(MarketPay marketPay) {
		this.marketPay = marketPay;
	}

	public BankInformation getBankInformation() {
		return bankInformation;
	}

	public void setBankInformation(BankInformation bankInformation) {
		this.bankInformation = bankInformation;
	}

	public KeyWord getKeyWord() {
		return keyWord;
	}

	public void setKeyWord(KeyWord keyWord) {
		this.keyWord = keyWord;
	}

	public Users getUsersFraudster() {
		return usersFraudster;
	}

	public void setUsersFraudster(Users usersFraudster) {
		this.usersFraudster = usersFraudster;
	}

	public Users getUsersRigged() {
		return usersRigged;
	}

	public void setUsersRigged(Users usersRigged) {
		this.usersRigged = usersRigged;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public DefectAnalysis getDefectAnalysis() {
		return defectAnalysis;
	}

	public void setDefectAnalysis(DefectAnalysis defectAnalysis) {
		this.defectAnalysis = defectAnalysis;
	}

	public Integer getLogCase() {
		return logCase;
	}

	public void setLogCase(Integer logCase) {
		this.logCase = logCase;
	}

	public Integer getPayId() {
		return payId;
	}

	public void setPayId(Integer payId) {
		this.payId = payId;
	}

	public String getStatusFraud() {
		return statusFraud;
	}

	public void setStatusFraud(String statusFraud) {
		this.statusFraud = statusFraud;
	}

	public String getTypeFraud() {
		return typeFraud;
	}

	public void setTypeFraud(String typeFraud) {
		this.typeFraud = typeFraud;
	}

	public String getProfileCase() {
		return profileCase;
	}

	public void setProfileCase(String profileCase) {
		this.profileCase = profileCase;
	}

	public String getOthesComments() {
		return othesComments;
	}

	public void setOthesComments(String othesComments) {
		this.othesComments = othesComments;
	}

	public Boolean getSolicitationData() {
		return solicitationData;
	}

	public void setSolicitationData(Boolean solicitationData) {
		this.solicitationData = solicitationData;
	}

	public Boolean getBuyerAnnounced() {
		return buyerAnnounced;
	}

	public void setBuyerAnnounced(Boolean buyerAnnounced) {
		this.buyerAnnounced = buyerAnnounced;
	}

	public Boolean getSendData() {
		return sendData;
	}

	public void setSendData(Boolean sendData) {
		this.sendData = sendData;
	}

	@Override
	public int hashCode() {
		return  this.identity == null ? 1 : this.identity.hashCode();	
	}

	@Override
	public boolean equals(Object obj) {		
		return obj instanceof Fraud && this.equals((Fraud)obj);
	}

	private boolean equals(Fraud other) {		
		return this.identity != null && this.identity.equals(other.identity);
	}	
	
}

Abraços…

R

Bom,

O que eu achei que era não é rssrsrsrs… o que pode estar acontecendo é que ele está tentando adicionar a constraint em sendo que ela já deva existir no schema… tente ver se tem no banco esse nome ou renomear essa constraint para ver se o erro continua…

B

Então eu pesquisei no google sobre isso e realmente o problema e de já existir a constraint(com nomes iguais), so que eu tenho que ter duas constrains(Com nomes diferentes) de User na tabela de Fraud. Uma ele cria, a outra eu so consegui criar na mão. Agora, por que o hibernate não consegue criar as duas constrains da mesma tabela?
Alguma ideia?

R

mesmo dando esse erro a foreign key não é criada?

B

Não, não é criada. Só consegui criando na mão

R

Olha… eu posso estar enganado… mas eu acho que vc usando a annotation ForeignKey está duplicando o comando com a annotation JoinColumn … já tentou tirar essa annotation e testar?

O joinColumn também gera foreign key

B

ralphsilver fiz o que você me falou. So que eu deixei um com a annotation ForeignKey e o outro não! Blz funcionou direito. So que no banco ele não fica com o nome certo. Tirando isso funcionou!

Valeu obrigado pela ajuda ficou assim:

@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "riggedIdentity",unique=false,nullable=false)  
	@ForeignKey(inverseName="identity",name="riggedIdentity")
	private Users usersRigged;
	
	@NotNull
	@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
	@JoinColumn(name = "fraudsterIdentity",unique=true,nullable=false)  
	//@ForeignKey(inverseName="identity",name="fraudsterIdentity")
	private Users usersFraudster;

Abraços a todos

R

eu também nunca consegui fazer o nome da chave ficar certo… sempre fica um nome grande… mas se funcionou… beleza… valew

B

Então colocando o @ForeignKey(inverseName=“identity”,name=“responsibleIdentity”) a chave fica com o nome bunitinho e tals… so nesse caso com duas chaves da mesma tabela que não rolou mas foi erro no banco de dados mesmo. Eu continuei tentando e teve um momento que deletei todo o banco pra gerar o erro, ai quando ia no banco criar o campo na mão, dava erro no momento de fazer o update na tabela. Mas coloca o @ForeignKey(inverseName=“identity”,name=“responsibleIdentity”) que fica bunito o nome!

Abraços e mais uma vez obrigado pela ajuda!

Criado 5 de abril de 2010
Ultima resposta 7 de abr. de 2010
Respostas 11
Participantes 2