• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Hibernate Composite Key With Foreign Key Problem

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
DROP TABLE IF EXISTS `spring_prod`.`tbl_club`;
CREATE TABLE `spring_prod`.`tbl_club` (
`CLUBID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`NAME` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`CLUBID`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 ROW_FORMAT=COMPRESSED;

DROP TABLE IF EXISTS `spring_prod`.`tbl_team`;
CREATE TABLE `spring_prod`.`tbl_team` (
`TEAMID` int(10) unsigned NOT NULL DEFAULT '0',
`CLUBID` int(10) unsigned NOT NULL DEFAULT '0',
`TEAMNAME` varchar(10) DEFAULT '',
`LUPDATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`TEAMID`,`CLUBID`),
KEY `index_2` (`CLUBID`),
CONSTRAINT `FK_tbl_team_1` FOREIGN KEY (`CLUBID`) REFERENCES `tbl_club` (`CLUBID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPRESSED;

__________________

package com.kruders.model.bean;

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.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**
* TblClub entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "tbl_club", catalog = "spring_prod")
public class TblClub implements java.io.Serializable {

// Fields

private Integer clubid;
private String name;
private Set<TblTeam> tblTeams = new HashSet<TblTeam>(0);

// Constructors

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

/** minimal constructor */
public TblClub(String name) {
this.name = name;
}

/** full constructor */
public TblClub(String name, Set<TblTeam> tblTeams) {
this.name = name;
this.tblTeams = tblTeams;
}

// Property accessors
@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "CLUBID", unique = true, nullable = false)
public Integer getClubid() {
return this.clubid;
}

public void setClubid(Integer clubid) {
this.clubid = clubid;
}

@Column(name = "NAME", nullable = false, length = 20)
public String getName() {
return this.name;
}

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

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "tblClub")
public Set<TblTeam> getTblTeams() {
return this.tblTeams;
}

public void setTblTeams(Set<TblTeam> tblTeams) {
this.tblTeams = tblTeams;
}

}
________________________________________________

package com.kruders.model.bean;

import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.ForeignKey;

/**
* TblTeam entity.
*/

@Entity
@Table(name = "tbl_team", catalog = "spring_prod")
public class TblTeam implements java.io.Serializable {

private TblTeamId id;
private TblClub tblClub;
private String teamname;
private Date lupdate;

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

/** minimal constructor */
public TblTeam(TblTeamId id, TblClub tblClub, Date lupdate) {
this.id = id;
this.tblClub = tblClub;
this.lupdate = lupdate;
}

/** full constructor */
public TblTeam(TblTeamId id, TblClub tblClub, String teamname, Date lupdate) {
this.id = id;
this.tblClub = tblClub;
this.teamname = teamname;
this.lupdate = lupdate;
}

// Property accessors
@EmbeddedId
@AttributeOverrides( {
@AttributeOverride(name = "teamid", column = @Column(name = "TEAMID", nullable = false)),
@AttributeOverride(name = "clubid", column = @Column(name = "CLUBID", nullable = false)) })
public TblTeamId getId() {
return this.id;
}

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

@ManyToOne(fetch = FetchType.LAZY)
@ForeignKey(name = "FK_tbl_team_1")

/*
* @JoinTable(name = "TBL_CLUB", joinColumns = { @JoinColumn(name =
* "clubid", referencedColumnName = "clubid") }, inverseJoinColumns =
* {@JoinColumn(name = "clubid", referencedColumnName = "clubid")})
*/

@JoinColumn(name = "CLUBID", nullable = false, insertable = false, updatable = false, referencedColumnName = "CLUBID")
public TblClub getTblClub() {
return this.tblClub;
}

public void setTblClub(TblClub tblClub) {
this.tblClub = tblClub;
}

@Column(name = "TEAMNAME", length = 10)
public String getTeamname() {
return this.teamname;
}

public void setTeamname(String teamname) {
this.teamname = teamname;
}

@Column(name = "LUPDATE", nullable = false, length = 19)
public Date getLupdate() {
return this.lupdate;
}

public void setLupdate(Date lupdate) {
this.lupdate = lupdate;
}

}
________________________________________

package com.kruders.model.bean;

import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
* TblTeamId entity.
*/
@Embeddable
public class TblTeamId implements java.io.Serializable {

// Fields

private Integer teamid;
private Integer clubid;

// Constructors

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

/** full constructor */
public TblTeamId(Integer teamid, Integer clubid) {
this.teamid = teamid;
this.clubid = clubid;
}

// Property accessors

@Column(name = "TEAMID", nullable = false)
public Integer getTeamid() {
return this.teamid;
}

public void setTeamid(Integer teamid) {
this.teamid = teamid;
}

@Column(name = "CLUBID", nullable = false)
public Integer getClubid() {
return this.clubid;
}

public void setClubid(Integer clubid) {
this.clubid = clubid;
}

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

return ((this.getTeamid() == castOther.getTeamid()) || (this
.getTeamid() != null
&& castOther.getTeamid() != null && this.getTeamid().equals(
castOther.getTeamid())))
&& ((this.getClubid() == castOther.getClubid()) || (this
.getClubid() != null
&& castOther.getClubid() != null && this.getClubid()
.equals(castOther.getClubid())));
}

public int hashCode() {
int result = 17;

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

}

-----------------------------------

package com.kruders.core;

import java.util.Date;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.hibernate.Session;

import com.kruders.model.bean.TblClub;
import com.kruders.model.bean.TblTeam;
import com.kruders.model.bean.TblTeamId;
import com.kruders.util.HibernateUtil;

public class Main {

public static void main(String[] args) {
Logger logger = new Main(Main.class, "file").getLogger(Main.class,
"file");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
TblClub club = new TblClub();
club.setName("Arsenal");

TblTeamId teamId = new TblTeamId();
teamId.setTeamid(1);
//teamId.setClubid(1);
TblTeam team = new TblTeam();
team.setId(teamId);
team.setTeamname("Team A");
team.setLupdate(new Date(System.currentTimeMillis()));

club.getTblTeams().add(team);

team.setTblClub(club);

session.saveOrUpdate(club);

session.getTransaction().commit();
}

public Main() {

}

public Main(Class cls, String pattern) {
PatternLayout layout = new PatternLayout();
DailyRollingFileAppender rollingAppender = new DailyRollingFileAppender();
if (pattern.equals("file")) {
rollingAppender.setLayout(layout);
}
logger = Logger.getLogger(cls);
logger.addAppender(rollingAppender);
}

Logger logger = null;

public Logger getLogger(Class cls, String pattern) {
PatternLayout layout = new PatternLayout();
DailyRollingFileAppender rollingAppender = new DailyRollingFileAppender();
if (pattern.equals("file")) {
rollingAppender.setLayout(layout);
}
logger = Logger.getLogger(cls);
logger.addAppender(rollingAppender);
return logger;
}
}

_______________________________________

I Got This Exception Please Resolve This Problem..

Hibernate:
select
max(CLUBID)
from
tbl_club
Hibernate:
select
tblteam_.CLUBID,
tblteam_.TEAMID,
tblteam_.LUPDATE as LUPDATE1_,
tblteam_.TEAMNAME as TEAMNAME1_
from
spring_prod.tbl_team tblteam_
where
tblteam_.CLUBID=?
and tblteam_.TEAMID=?
[TRACE] 2013-08-03 15:14:33 BasicBinder:71 - binding parameter [1] as [INTEGER] - <null>
[TRACE] 2013-08-03 15:14:33 BasicBinder:83 - binding parameter [2] as [INTEGER] - 1
Hibernate:
insert
into
spring_prod.tbl_club
(NAME, CLUBID)
values
(?, ?)
[TRACE] 2013-08-03 15:14:33 BasicBinder:83 - binding parameter [1] as [VARCHAR] - Arsenal
[TRACE] 2013-08-03 15:14:33 BasicBinder:83 - binding parameter [2] as [INTEGER] - 1
Hibernate:
insert
into
spring_prod.tbl_team
(LUPDATE, TEAMNAME, CLUBID, TEAMID)
values
(?, ?, ?, ?)
[TRACE] 2013-08-03 15:14:33 BasicBinder:83 - binding parameter [1] as [TIMESTAMP] - Sat Aug 03 15:14:33 IST 2013
[TRACE] 2013-08-03 15:14:33 BasicBinder:83 - binding parameter [2] as [VARCHAR] - Team A
[TRACE] 2013-08-03 15:14:33 BasicBinder:71 - binding parameter [3] as [INTEGER] - <null>
[TRACE] 2013-08-03 15:14:33 BasicBinder:83 - binding parameter [4] as [INTEGER] - 1
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Column 'CLUBID' cannot be null
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:128)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at $Proxy19.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2859)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3300)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:275)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1214)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:403)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at com.kruders.core.Main.main(Main.java:39)
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'CLUBID' cannot be null
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1169)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:693)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1404)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1318)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1303)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 16 more
[WARN ] 2013-08-03 15:14:34 SqlExceptionHelper:143 - SQL Error: 1048, SQLState: 23000
[ERROR] 2013-08-03 15:14:34 SqlExceptionHelper:144 - Column 'CLUBID' cannot be null


 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic