Announcement Announcement Module
Collapse
No announcement yet.
Problem with Null identifier using Hibernate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Problem with Null identifier using Hibernate

    Hey Everyone,

    Right off the bat, here is the error message:

    exception is org.hibernate.TransientObjectException: The given object has a null identifier: com.ryans.MVCproject1.Team]

    I am just making a small CRUD program to learn about hibernate and Spring. This little program has a service layer (baseballServiceImp.java) that is going through the DAO layer (baseballDAOimp.java) to get to the DB. I have debugged the app and found that the primary key in my "Team" table is null when the program goes to persist. I do not know why it is still null when I have told hibernate to auto-generate a value for the primary key. So I must not have something setup correctly in my project. Please help. The code is as follows:

    Servlet-context.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    
    	<!-- DispatcherServlet Context: defines this servlet's request-processing 
    		infrastructure -->
    
    	<!-- Enables the Spring MVC @Controller programming model -->
    	<annotation-driven />
    	<!-- Enables the transactional annotations -->
    	<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    
    	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    		up static resources in the ${webappRoot}/resources directory -->
    	<resources mapping="/resources/**" location="/resources/" />
    
    	<!-- Connection to Database -->
    	<beans:bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    		<beans:property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    		<beans:property name="url" value="jdbc:hsqldb:C:\SpringProjects\MVCProj1\databaseMLB" />
    		<beans:property name="username" value="ryan" />
    		<beans:property name="password" value="ryan" />
    	</beans:bean>
    
    	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
    		in the /WEB-INF/views directory -->
    	<!-- View Resolver -->
    	<beans:bean
    		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<beans:property name="prefix" value="/WEB-INF/views/" />
    		<beans:property name="suffix" value=".jsp" />
    	</beans:bean>
    
    	<!-- MessageSource -->
    	<beans:bean
    		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    		<beans:property name="basename" value="classpath:messages" />
    		<beans:property name="defaultEncoding" value="UTF-8" />
    	</beans:bean>
    
    	<!-- Hibernate SessionFactory -->
    	<beans:bean id="sessionFactory"
    		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<beans:property name="dataSource" ref="datasource"></beans:property>
    		<beans:property name="configLocation" value="classpath:hibernate.cfg.xml"></beans:property>
    		<beans:property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"></beans:property>
    		<beans:property name="hibernateProperties">
    			<beans:props>
    				<beans:prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</beans:prop>
    				<beans:prop key="hibernate.show_sql">true</beans:prop>
    				<beans:prop key="hibernate.hbm2dll.auto">create</beans:prop>
    			</beans:props>
    		</beans:property>
    	</beans:bean>
    	
    	 <!-- Define a transaction Manager -->
    	<beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    	<beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
    	</beans:bean>
    	
    	
    	<beans:bean id="theTeam" class="com.ryans.MVCproject1.Team"></beans:bean>
    	
    	<beans:bean id="baseballDAO" class="com.ryans.MVCproject1.BaseballDAOimp">
    	<beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
    	</beans:bean> 
    	
    	
    	<beans:bean id="teamManager" class="com.ryans.MVCproject1.baseballServiceImp">
    	<beans:constructor-arg ref="baseballDAO"></beans:constructor-arg>
    	</beans:bean> 
    
    	<!-- Transaction Manager -->
    
    	<beans:bean
    		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
    	</beans:bean>
    
    	<context:component-scan base-package="com.ryans.MVCproject1" />
    
    </beans:beans>
    hibernate.cgf.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     
    <hibernate-configuration>
        <session-factory>
            <mapping package="com.ryans.MVCproject1" />
            <mapping class="com.ryans.MVCproject1.Player"/>
            <mapping class="com.ryans.MVCproject1.Team"/>
        </session-factory>
     
    </hibernate-configuration>
    baseballDAOimp.java
    Code:
    package com.ryans.MVCproject1;
    
    import java.util.List;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.*;
    import org.hibernate.classic.Session;
    
    @Repository
    public class BaseballDAOimp implements BaseballDAO {
    
    	@Autowired
    	private SessionFactory sessionFactory; //the hibernate object
    	
    	@Autowired
    	public BaseballDAOimp(SessionFactory sessionFactory){
    		this.setSessionFactory(sessionFactory);
    	}
    	
    	private Session currentSession(){
    		return getSessionFactory().getCurrentSession(); //get the current hibernate session
    	}
    	
    
    	public void saveTeam(Team theTeam){
    		currentSession().update(theTeam);
    	}	
    	
    	public void addPlayer(Player theNewPlayer) {
    		getSessionFactory().getCurrentSession().save(theNewPlayer);
    	
    	}
    
    	public void addTeam(Team theNewTeam) {
    		getSessionFactory().getCurrentSession().save(theNewTeam);
    	}
    
    	public void removePlayer(String lastName) {
    		Player player = (Player)getSessionFactory().getCurrentSession().load(Player.class, lastName);
    		/* A class literal (e.g. Hashtable.class) is a notation which represents an 
    		 * instance of the class Class. The currentSession will know what kind of object
    		 * it is loading.
    		 */
    		if(player != null)
    			getSessionFactory().getCurrentSession().delete(player);
    	}
    
    	public void removeTeam(String teamName) {
    		Team team = (Team) getSessionFactory().getCurrentSession().load(Team.class, teamName);
    		/* A class literal (e.g. Hashtable.class) is a notation which represents an 
    		 * instance of the class Class. The currentSession will know what kind of object
    		 * it is loading.
    		 */
    		if(team != null)
    			getSessionFactory().getCurrentSession().delete(team);
    	}
    	
    
    	public List<Player> getAllPlayers() {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	public List<Team> getAllTeams() {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	public Player findPlayerByLastName(String lastName) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	public Team findTeamByCity(String cityName) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    
    	public SessionFactory getSessionFactory() {
    		return sessionFactory;
    	}
    
    	public void setSessionFactory(SessionFactory sessionFactory) {
    		this.sessionFactory = sessionFactory;
    	}	
    
    }
    team.java
    Code:
    package com.ryans.MVCproject1;
    
    import java.util.*;
    import javax.persistence.*;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    @Entity
    @Table(name="TEAM")
    public class Team {
    	
    	@Column(name="ID")
    	@Id
    	@GeneratedValue
    	private Integer id; //id makes all teams unique
    	
    	@Column(name="TEAMNAME")
    	private String teamName; //the name of the team
    	@Column(name="CITY")
    	private String city; //where the team plays
    	@Column(name="TEAMMEMBERS", nullable=true)
    	@OneToMany(mappedBy="playerTeam")
    	private Collection<Player> teamMembers; //players on this team 
    			
    	public String getTeamName() {
    		return teamName;
    	}
    
    	public void setTeamName(String teamName) {
    		this.teamName = teamName;
    	}
    	public String getCity() {
    		return city;
    	}
    	
    	public void setCity(String city) {
    		this.city = city;
    	}
    	
    	public Collection<Player> getTeamMembers() {
    		return teamMembers;
    	}
    	
    	public void setTeamMembers(Collection<Player> teamMembers) {
    		this.teamMembers = teamMembers;
    	}
    	public Integer getId() {
    		return id;
    	}
    	public void setId(Integer id) {
    		this.id = id;
    	}
    }
    baseballServiceImp.java
    Code:
    package com.ryans.MVCproject1;
    
    import org.springframework.beans.factory.annotation.*;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class baseballServiceImp implements baseballService {
    
    	@Autowired
    	private BaseballDAO baseballDAO; //the DAO object to access the transactions of the db
    	@Autowired
    	public baseballServiceImp(BaseballDAO baseballDAO){
    		this.baseballDAO = baseballDAO;
    	}
    	@Transactional
    	public void addPlayer(Player player) {
    		baseballDAO.addPlayer(player);	
    	}
    	
    	@Transactional
    	public void removePlayer(String lastName) {
    		baseballDAO.removePlayer(lastName);
    	}
    	@Transactional
    	public void addTeam(Team team) {
    		baseballDAO.addTeam(team);
    	}
    	@Transactional
    	public void removeTeam(String teamName) {
    		baseballDAO.removeTeam(teamName);
    	}
    	@Transactional
    	public void saveTeam(Team theTeam){
    		baseballDAO.saveTeam(theTeam);	
    	}
    	public BaseballDAO getBaseballDAO() {
    		return baseballDAO;
    	}
    	public void setBaseballDAO(BaseballDAO baseballDAO) {
    		this.baseballDAO = baseballDAO;
    	}	
    }
    Thanks as always.

  • #2
    In my DAO Implementation, I was using save instead of update for the add team method. I didn't realize these were two different functions. Update creates the record, while save updates an existing record. If I have that wrong then please let me know.

    Comment

    Working...
    X