-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 
Author Message
 Post subject: Adding Objects To MySQL
PostPosted: Thu Sep 02, 2004 6:22 am 
Newbie

Joined: Tue Aug 24, 2004 1:14 pm
Posts: 14
Hibernate version:
2.1.6
Mapping documents:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration. -->
<!-- Created Thu Sep 02 11:08:29 BST 2004 -->
<hibernate-mapping package="co.uk.fastest.foi.hibernate">

<class name="Users" table="Users">
<id name="usersId" column="users_id" type="java.lang.String">
<generator class="native"/>
</id>

<property name="usersUsername" column="users_username" type="java.lang.String" not-null="true" />
<property name="usersPassword" column="users_password" type="java.lang.String" not-null="true" />
<property name="usersLevel" column="users_level" type="java.lang.String" not-null="true" />
<property name="usersEmail" column="users_email" type="java.lang.String" not-null="true" />
<property name="usersDepartment" column="users_department" type="java.lang.String" not-null="true" />
<property name="usersTitle" column="users_title" type="java.lang.String" not-null="true" />
<property name="usersJobTitle" column="users_job_title" type="java.lang.String" />
<property name="usersFirstName" column="users_first_name" type="java.lang.String" not-null="true" />
<property name="usersInitials" column="users_initials" type="java.lang.String" not-null="true" />
<property name="usersSurname" column="users_surname" type="java.lang.String" not-null="true" />
<property name="usersTelephone" column="users_telephone" type="java.lang.String" not-null="true" />
<property name="usersGenPassword" column="users_gen_password" type="java.lang.String" not-null="true" />
<property name="usersLastLogin" column="users_last_login" type="java.util.Date" />
</class>

</hibernate-mapping>

drop table if exists Users;
create table Users
(
users_id int unsigned not null primary key,
users_username varchar(10) not null,
users_password varchar(10) not null,
users_level int unsigned not null,
users_email varchar(125) not null,
users_department varchar(50) not null,
users_title varchar(5) not null,
users_job_title varchar(100),
users_first_name varchar(25) not null,
users_initials varchar(5) not null,
users_surname varchar(25) not null,
users_telephone bigint unsigned not null,
users_gen_password varchar(10) not null,
users_last_login date
);

<hibernate-configuration>

<session-factory>
<!-- properties -->
<property name="connection.username">rbbh</property>
<property name="connection.url">jdbc:mysql://localhost:3306/rbbh_freedom</property>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="connection.password">battle</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

<!-- mapping files -->
<mapping resource="co/uk/fastest/foi/hibernate/Users.hbm.xml"/>

</session-factory>

</hibernate-configuration>
Code between sessionFactory.openSession() and session.close():

package co.uk.fastest.foi.hibernate;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class HibernateSessionFactory {

/**
* Location of hibernate.cfg.xml file.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

/** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal();

/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();

/** The single instance of hibernate SessionFactory */
private static net.sf.hibernate.SessionFactory sessionFactory;

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}

return session;
}

/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
* Default constructor.
*/
private HibernateSessionFactory() {
}

}

public void addUsers ( Users user ) { // start of the addUsers method

// Create the insance that will be the database session
Session session = null;

try { // start of the try statement

session = HibernateSessionFactory.currentSession();
session.save(user);
session.flush();

} // end of the try statement

catch ( HibernateException e ) { // start of the catch exception

throw new RuntimeException ( e );

} // end of the catch exception

finally { // start of the finally statement

if ( session != null ) { // start of if statement

try { // start of the try statement

session.close ( );

} // end of the try statement

catch ( HibernateException e ) { // start of the catch statement

throw new RuntimeException ( e );

} // end of the catch statement

} // end of the if statement

} // end of the finally statement

} // end of the addUsers method

Full stack trace of any exception that occurs:
The first time it is run
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.RuntimeException: net.sf.hibernate.HibernateException: The database returned no natively generated identity value
at co.uk.fastest.foi.hibernate.Database.addUsers(Database.java:162)
at Application.<init>(Application.java:36)
at Application.main(Application.java:48)
Caused by: net.sf.hibernate.HibernateException: The database returned no natively generated identity value
at net.sf.hibernate.persister.AbstractEntityPersister.getGeneratedIdentity(AbstractEntityPersister.java:1230)
at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:530)
at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:432)
at net.sf.hibernate.impl.ScheduledIdentityInsertion.execute(ScheduledIdentityInsertion.java:29)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:932)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:857)
at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:775)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:738)
at co.uk.fastest.foi.hibernate.Database.addUsers(Database.java:155)
... 2 more
The second time it is run
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.RuntimeException: net.sf.hibernate.JDBCException: could not insert: [co.uk.fastest.foi.hibernate.Users]
at co.uk.fastest.foi.hibernate.Database.addUsers(Database.java:162)
at Application.<init>(Application.java:36)
at Application.main(Application.java:48)
Caused by: net.sf.hibernate.JDBCException: could not insert: [co.uk.fastest.foi.hibernate.Users]
at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:558)
at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:432)
at net.sf.hibernate.impl.ScheduledIdentityInsertion.execute(ScheduledIdentityInsertion.java:29)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:932)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:857)
at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:775)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:738)
at co.uk.fastest.foi.hibernate.Database.addUsers(Database.java:155)
... 2 more
Caused by: java.sql.SQLException: Duplicate key or integrity constraint violation, message from server: "Duplicate entry '0' for key 1"
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1977)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1163)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1272)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2236)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1741)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1588)
at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:528)
... 9 more


Name and version of the database you are using:
MySQL normal 4.0.20

This is really odd as it does add the object to the database and then throws an error, and then when you call the code again the error is in generating a primary key, here is the code i called.

public class Application {

public Application () {

Users user = new Users();

user.setUsersDepartment("programming");
user.setUsersEmail("tom.malone@fastest.org.uk");
user.setUsersFirstName("thomas");
user.setUsersGenPassword("password");
user.setUsersInitials("tjm");
user.setUsersJobTitle("programmer");
user.setUsersLevel("1");
user.setUsersPassword("liverpool");
user.setUsersSurname("malone");
user.setUsersTelephone("01635254795");
user.setUsersTitle("tjm");
user.setUsersUsername("fred");

Database.getInstance().addUsers(user);
System.out.println("set the user to null");
user = null;

user = Database.getInstance().getUsers("tom");

System.out.println(user.getUsersDepartment());

}


public static void main ( String args[] ) {
new Application ( );
}

}

So why are these two errors called, sorry if this is blindingly obvious i am really stuck any suggestions or help would be greattly appreciated.

Tom


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 02, 2004 6:28 am 
Regular
Regular

Joined: Mon Feb 23, 2004 10:42 pm
Posts: 102
Location: Washington DC
Check your mapping type for the users_id. You have it set to string, yet the table has users_id as an int.

_________________
Matt Veitas


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 02, 2004 6:32 am 
Regular
Regular

Joined: Thu Aug 05, 2004 2:27 am
Posts: 54
Location: South Africa
your mapping says the id for users is "native", but your create table does not include "AUTO_INCREMENT".
change the mapping for your id, it should be int.


Top
 Profile  
 
 Post subject: not sure
PostPosted: Thu Sep 02, 2004 6:33 am 
Newbie

Joined: Tue Aug 24, 2004 1:14 pm
Posts: 14
I use myeclipseide to generte the mapping files but of you look at the code to set the id it does not use strings

public void setUsersId(java.lang.String usersId)
{
this.hashValue = 0;
this.usersId = usersId;
}


Top
 Profile  
 
 Post subject: if change to auto_increment
PostPosted: Thu Sep 02, 2004 6:56 am 
Newbie

Joined: Tue Aug 24, 2004 1:14 pm
Posts: 14
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.RuntimeException: net.sf.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short
at co.uk.fastest.foi.hibernate.Database.addUsers(Database.java:162)
at Application.<init>(Application.java:37)
at Application.main(Application.java:49)
Caused by: net.sf.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short
at net.sf.hibernate.id.IdentifierGeneratorFactory.get(IdentifierGeneratorFactory.java:38)
at net.sf.hibernate.persister.AbstractEntityPersister.getGeneratedIdentity(AbstractEntityPersister.java:1231)
at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:530)
at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:432)
at net.sf.hibernate.impl.ScheduledIdentityInsertion.execute(ScheduledIdentityInsertion.java:29)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:932)
at net.sf.hibernate.impl.SessionImpl.doSave(SessionImpl.java:857)
at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:775)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:738)
at co.uk.fastest.foi.hibernate.Database.addUsers(Database.java:155)
... 2 more


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.