Question on persistence
I would like to know if using JPA/hibernate would be better than simple JDBC?
The reason why I am asking is, Hibernate would have the caching/pooling..
Where as JDBC its plain connection ....
I would like to know your inputs
thanks
Yes, you'll find it a lot easier to use a higher-level persistence API than to use JDBC directly.
The persistence runtime can also give you much better performance because it
knows more about what your application is trying to do. Finally, using a higher-level
persistence API isolates your code from using native SQL.
Now that the Java Persistence API is available I would recommend it over Hibernate. Most of
the functionality from Hibernate has been incorporated into the standard. Writing to that
API will give you more flexibility in choosing different persistence implementations should you
need to do that in the future.
You can find more information on the Java Persistence API in the Java EE 5 tutorial :
http://java.sun.com/javaee/5/docs/tutorial/doc/
And here's the home page for the Persistence implementation in the Java EE 5 SDK :
https://glassfish.dev.java.net/javaee5/persistence/
--ken
Similar Messages
-
Question on Persistence (Entity Beans, Hibernate, JDBC)
Hi everybody!
Until now, I have read a lot about persistence in the J2EE-sector, but I am still confused about which technology to used in my case.
I hope, that maybe you can give me some hints, by telling me which technology is good or bad regarding my requirements:
I want to build a customer- and order-management system fullfilling the following requirements:
1. The client is a Java application, the server is a JBOSS 4.0.1
2. The databasa scheme exists already and I'm not allowed to change it.
Some data, that logically belongs together and which shall be presented together to the client is distributed over 2 database tables.
3. The user cannot just create new and view data, but will also edit existing data quite often.
4. The user can assign products to an order. Often, there will be more than 1000 products assigned to an order, which will be presented to the user as a table (e.g. JTable). The user can then edit each cell of that 1000-row table, which of course will lead to an update in the db.
5. The user can also assign customers to a specific role in an order-process. On the other hand, each customer can make many orders.
So, we have a n:m relation here with the db-tables Customer, Order, OrderCustomer.
6. A complex search functionality has to be implemented, where the db-query is created dynamically at runtime.
7. The application is a multi-user application (about 10 users). It will be very rare, that users will work on the same data at the same time, but it might happen.
8. The database type (SAP DB) will not be changed in the near future.
With these 8 requirements in mind, I dealed a lot with EntityBeans, Hibernate and JDBC with SesseionBeans during the last 2 weeks.
Until now, I came to the following conclusions.
Hibernate is too slow. That'S bad, for data is edited very often and sometimes I want to edit just a single cell in 1000-row table.
Hibernate's biggest advantage - that it makes your application independent of the database type - is not even required (see point 8).
JDBC with SessioBeans: Very fast (I tried a simple query and it was about 10 times faster than Hibernate).
The disadvantage is, that I have to take care about all the transaction, concurrency control etc. things.
If I use JDBC, I want to do it that way: A SessionFacade accesses a DAO-object which executes the DB-query and returns the result to the SessionFacade which in the last step will pass the result to the client.
Entity Beans: I am completely confused with Entity Beans.
I read a lot about the CompositeEntity-Pattern for BMP. But on sun's J2EE Pattern page (http://java.sun.com/blueprints/corej2eepatterns/Patterns/CompositeEntity.html)
they said, that it's just useful when using the EJB 1.1 specification, because from EJB 2.0. the container or whatever will take care about lazy loading and store optimization.
So, from EJB 2.0. you should prefer using CMP-Beans with Container Managed Relationships (CMR), but as I heard, the dependent objects cannot be accessed and changed by the client when using CMPBeans with CMR.
However, a simple DB/Entity-mapping will not work in my case, because as mentioned above, there are thousands of products from the db to be managed at the same time. So here, I thought, the Composite pattern with its lazy loading strategy would be useful.
Furthermore, I have an n:m relationship in my database scheme, which is not trivial to map to entity beans. And don't forget that some related data is spread over 2 databse tables.
To sum it up, it would be very nice if some of you could clarify this perisistence nightmare, especially some clarification about if and how to use EntityBeans when having n:m relationships, editing data a lot, managing lots of table rows at once and having related data distributed over 2 database tables.
So, which technology would you prefer with the 8 requirements in mind? Hibernate, Entity Beans or JDBC with SessionBeans? Or would you prefer a mixed solution?
Thanx for every hint.
Regards,
egonHere the requested information about the test:
Goal:
Find all customers, who's branches have the String "Branch" in their name.
Both times, a simple client accesses the same SessionBean in a JBOSS-Container.
This Bean has 2 methods. One accesses the DB via Hibernate (executeCriteria), the other one via JDBC (executeCriteriaJDBC).
The code to count the seconds of computation is as follows:
long startTime = System.currentTimeMillis();
List customerList = bean.executeCriteria(dc);
System.out.println("Hibernate: "+((System.currentTimeMillis()-startTime)/1000.0f)+" sek");
startTime = System.currentTimeMillis();
List customerListJDBC = bean.executeCriteriaJDBC(query);
System.out.println("JDBC: "+((System.currentTimeMillis()-startTime)/1000.0f)+" sek");
HIBERNATE:
CODE:
Branch Branch = new Branch();
Branch.setName("%Branch%");
Example example = Example.create(Branch);
DetachedCriteria dc = DetachedCriteria.forClass(Customer.class)
.createCriteria("branches").add(example.enableLike()).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
QUERY:
select
this_.UUID as UUID1_1_,
this_.NAME as NAME1_1_,
this_.CUSTOMERNO as CUSTOMERNO1_1_,
this_.SHORTDESC as SHORTDESC1_1_,
this_.LONGDESC as LONGDESC1_1_,
this_.TAXNUMBER as TAXNUMBER1_1_,
this_.SALESTAXID as SALESTAXID1_1_,
this_.ACCOUNTHOLDER as ACCOUNTH8_1_1_,
this_.BANKACCOUNT as BANKACCO9_1_1_,
this_.BANKCODE as BANKCODE1_1_,
this_.BANKNAME as BANKNAME1_1_,
this_.AREA1TEXT as AREA12_1_1_,
this_.AREA2TEXT as AREA13_1_1_,
this_.AREA3TEXT as AREA14_1_1_,
this_.AREA4TEXT as AREA15_1_1_,
this_.AREA5TEXT as AREA16_1_1_,
this_.CH_UUID as CH17_1_1_,
this_.REFTEXT1 as REFTEXT18_1_1_,
this_.REFTEXT2 as REFTEXT19_1_1_,
this_.REFTEXT3 as REFTEXT20_1_1_,
branch1_.UUID as UUID0_0_,
branch1_.NAME as NAME0_0_,
branch1_.ILN as ILN0_0_,
branch1_.BRANCHID as BRANCHID0_0_,
branch1_.SHORTDESC as SHORTDESC0_0_,
branch1_.LONGDESC as LONGDESC0_0_,
branch1_.BAGSRECEIVED as BAGSRECE7_0_0_,
branch1_.CUSTOMER_UUID as CUSTOMER8_0_0_
from
CUSTOMER this_,
BRANCH branch1_
where
this_.UUID=branch1_.CUSTOMER_UUID
and (
branch1_.NAME like ?
RESULT:
Customername: Customer_A
Customername: Customer_F
Customername: Customer_D
Customername: Customer_R
Customername: Customer_S
TIME:
Hibernate: 1.343 sek
JDBC:
QUERY:
Select distinct c.* from Customer c, Branch b where b.id=b.Customer_id and b.name like '%Branch%'
// After getting the result of the query: Create a list of Customer-objects. Set all attributes of each Customer-object.
RESULT:
Customername: Customer_R
Customername: Customer_A
Customername: Customer_S
Customername: Customer_D
Customername: Customer_F
TIME:
JDBC: 0.125 sek
The Customer.hbm.xml (auto-generated in Eclipse with Middlegen)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<!--
Created by the Middlegen Hibernate plugin 2.2
http://boss.bekk.no/boss/middlegen/
http://www.hibernate.org/
-->
<class
name="hibernate.hibernate.Customer"
table="CUSTOMER"
lazy="false"
>
<id
name="uuid"
type="java.lang.String"
column="UUID"
>
<generator class="assigned" />
</id>
<property
name="name"
type="java.lang.String"
column="NAME"
length="100"
/>
<property
name="customerno"
type="java.lang.Integer"
column="CUSTOMERNO"
length="5"
/>
<property
name="shortdesc"
type="java.lang.String"
column="SHORTDESC"
length="50"
/>
<property
name="longdesc"
type="java.lang.String"
column="LONGDESC"
length="100"
/>
<property
name="taxnumber"
type="java.lang.String"
column="TAXNUMBER"
length="50"
/>
<property
name="salestaxid"
type="java.lang.String"
column="SALESTAXID"
length="50"
/>
<property
name="accountholder"
type="java.lang.String"
column="ACCOUNTHOLDER"
length="50"
/>
<property
name="bankaccount"
type="java.lang.String"
column="BANKACCOUNT"
length="50"
/>
<property
name="bankcode"
type="java.lang.String"
column="BANKCODE"
length="50"
/>
<property
name="bankname"
type="java.lang.String"
column="BANKNAME"
length="50"
/>
<property
name="area1text"
type="java.lang.String"
column="AREA1TEXT"
length="50"
/>
<property
name="area2text"
type="java.lang.String"
column="AREA2TEXT"
length="50"
/>
<property
name="area3text"
type="java.lang.String"
column="AREA3TEXT"
length="50"
/>
<property
name="area4text"
type="java.lang.String"
column="AREA4TEXT"
length="50"
/>
<property
name="area5text"
type="java.lang.String"
column="AREA5TEXT"
length="50"
/>
<property
name="chUuid"
type="java.lang.String"
column="CH_UUID"
length="50"
/>
<property
name="reftext1"
type="java.lang.String"
column="REFTEXT1"
length="50"
/>
<property
name="reftext2"
type="java.lang.String"
column="REFTEXT2"
length="50"
/>
<property
name="reftext3"
type="java.lang.String"
column="REFTEXT3"
length="50"
/>
<!-- Associations -->
<!-- bi-directional one-to-many association to Branch -->
<set
name="branches"
lazy="true"
inverse="true"
cascade="all"
>
<key>
<column name="CUSTOMER_UUID" />
</key>
<one-to-many
class="hibernate.hibernate.Branch"
/>
</set>
</class>
</hibernate-mapping>So, seems to me like Hibernate is also getting the data from the Branch-Table related to each Customer. Maybe this is the reason, why Hibernate is slower.
But as you can see in the mapping-File of the customer, I wanted Branches to be lazy loaded.
Do you have any ideas, why Hibernate is so much slower? Any hints for optimizing that code?
Do you have any further tricks to optimize Hibernate? Unfortunately I am not allowed to make changes at the database, so I cannot e.g. set indices for optimization.
However, I�m a Hibernate-Newbie. In fact, I just made this test and was very disappointed about its result, so I didn�t keep on working with Hibernate.
But maybe you can proof me, that Hibernate is a good choice. If so, do you have any good resources (links, books) that help working with Hibernate in connection with JBOSS, describe how to map n:m relationships, show how to work with large results and so forth?
Thanx for help,
egon -
Question about persistence.xml
Hi,
I have two persistence units in one persistence.xml file. When I deploy my ejb3 file, my Car entity bean (@Entity) creates two tables in the database (one for each persistence-unit). I want the table created in only one persistence-unit. How I tell to the entity bean what persistence-unit it has to use and what it has not?
Thanks
Luiz CarlosOk,
I find a way.
All I have to do was put the property
<property name="hibernate.archive.autodetection" value="false"/>
in the persistence.xml and define the classes I wanna to use with
<class>SomeClass</class>
<class>AnotherClass</class>
It was too much work but was the only way I found..
Thanks anyway
Luiz Carlos -
Persistence by reachability with FK in PK
Hi,
I have a question concerning persistence-by-reachability in the
following scenario (also see code, log in attachment):
+ A composite aggregation between Attribute and AttributeType (Attribute
cannot be created without a valid Type) is mapped to the following schema:
CREATE TABLE ATTRIBUTE_TYPE (
ID NUMBER (4) NOT NULL,
TYPE NUMBER (2) NOT NULL,
CONSTRAINT ATTRIBUTE_TYPE_PK
PRIMARY KEY ( ID ) ) ;
CREATE TABLE ATTRIBUTE (
CLASS_ID NUMBER(4) NOT NULL,
TYPE_ID NUMBER (4) NOT NULL,
VALUE VARCHAR2 (100) NOT NULL,
CONSTRAINT ATTRIBUTE_PK
PRIMARY KEY ( CLASS_ID, TYPE_ID ) ) ;
ALTER TABLE ATTRIBUTE ADD CONSTRAINT ATTRIBUTE_FK
FOREIGN KEY (TYPE_ID)
REFERENCES ATTRIBUTE_TYPE (ID) ;
+ In the constructor of Attribute, the AttributeType is given as
parameter and both the instance variable type as typeId is set (and
type.getId() == typeId). Both classes use Application Identity.
private AttributeType type;
private int typeId;
private String value;
private int classId;
public Attribute(int pClassId, AttributeType pType, String pValue) {
this.classId = pClassId;
this.typeId = pType.getId();
this.type = pType;
this.value = pValue;
+ So, when persisting a new instance of Attribute of a new AttributeType
the ATTRIBUTE_FK constraint is violated:
javax.jdo.PersistentManager pm = ...
pm.currentTransaction().begin();
pm.makePersistent(new Attribute(10,new AttributeType(50,10),"KODO")));
pm.currentTransaction().commit();
According to the JDO Specification AttributeType is part of the object
closure of Attribute and is marked provisionally persistent by the
'Persistence-by-reachability' algorithm and made persistent at commit.
Apparently KODO doesn't take the FK constraint into account to derive
the order in which to make classes persistent. Is this assumption
correct? And is there a workaround for this?
Thanks in advance,
Stijn Van den EndenAssuming we're talking about Oracle, using deferred constraints has the
undesirable effect of forcing use of a non-unique index to enforce the FK
constraint.
Is there any other way with 2.5.5 to get Kodo to insert to the parent table,
and delete from the child tables first ?
Regards,
Chris.
"Stijn Van den Enden" <[email protected]> wrote in message
news:[email protected]...
Hi,
thanks a lot!
Marking the FK constraint as Defferable works fine for me.
ALTER TABLE ATTRIBUTE ADD CONSTRAINT ATTRIBUTE_FK
FOREIGN KEY (TYPE_ID)
REFERENCES ATTRIBUTE_TYPE (ID)
DEFERRABLE INITIALLY DEFERRED;
Thanx,
Stijn Van den Enden
Stephen Kim wrote:
Kodo 2.5.x does not do foreign key constraint analysis. You should
either use deferred database constraints (supported on several dbs) or
try using Kodo 3 (in RC stage) which can optionally do so (it is
disabled by default since it could have performance impact (analyzing
instead of simply executing SQL)).
Stijn Van den Enden wrote:
Hi,
I have a question concerning persistence-by-reachability in the
following scenario (also see code, log in attachment):
+ A composite aggregation between Attribute and AttributeType
(Attribute cannot be created without a valid Type) is mapped to the
following schema:
CREATE TABLE ATTRIBUTE_TYPE (
ID NUMBER (4) NOT NULL,
TYPE NUMBER (2) NOT NULL,
CONSTRAINT ATTRIBUTE_TYPE_PK
PRIMARY KEY ( ID ) ) ;
CREATE TABLE ATTRIBUTE (
CLASS_ID NUMBER(4) NOT NULL,
TYPE_ID NUMBER (4) NOT NULL,
VALUE VARCHAR2 (100) NOT NULL,
CONSTRAINT ATTRIBUTE_PK
PRIMARY KEY ( CLASS_ID, TYPE_ID ) ) ;
ALTER TABLE ATTRIBUTE ADD CONSTRAINT ATTRIBUTE_FK
FOREIGN KEY (TYPE_ID)
REFERENCES ATTRIBUTE_TYPE (ID) ;
+ In the constructor of Attribute, the AttributeType is given as
parameter and both the instance variable type as typeId is set (and
type.getId() == typeId). Both classes use Application Identity.
private AttributeType type;
private int typeId;
private String value;
private int classId;
public Attribute(int pClassId, AttributeType pType, String pValue) {
this.classId = pClassId;
this.typeId = pType.getId();
this.type = pType;
this.value = pValue;
+ So, when persisting a new instance of Attribute of a new
AttributeType the ATTRIBUTE_FK constraint is violated:
javax.jdo.PersistentManager pm = ...
pm.currentTransaction().begin();
pm.makePersistent(new Attribute(10,new AttributeType(50,10),"KODO")));
pm.currentTransaction().commit();
According to the JDO Specification AttributeType is part of the object
closure of Attribute and is marked provisionally persistent by the
'Persistence-by-reachability' algorithm and made persistent at commit.
Apparently KODO doesn't take the FK constraint into account to derive
the order in which to make classes persistent. Is this assumption
correct? And is there a workaround for this?
Thanks in advance,
Stijn Van den Enden
DEBUG [main] (JDBCPersistenceManagerFactory.java:241) -
[email protected]b9:
setup
DEBUG [main] (JDBCPersistenceManagerFactory.java:241) -
[email protected]b9:
setup
INFO [main] (LicenseChecker.java:162) - Starting Kodo JDO version
2.5.4 (kodojdo-2.5.4-20031001-1134) with capabilities: [Enterprise
Edition Features, Standard Edition Features, Lite Edition Features,
Evaluation License, Query Extensions, Performance Pack, Statement
Batching, Global Transactions, Developer Tools, Custom Database
Dictionaries, Enterprise Databases, Custom ClassMappings, Custom
ResultObjectProviders, Datacache Plug-in]
INFO [main] (LicenseChecker.java:162) - Starting Kodo JDO version
2.5.4 (kodojdo-2.5.4-20031001-1134) with capabilities: [Enterprise
Edition Features, Standard Edition Features, Lite Edition Features,
Evaluation License, Query Extensions, Performance Pack, Statement
Batching, Global Transactions, Developer Tools, Custom Database
Dictionaries, Enterprise Databases, Custom ClassMappings, Custom
ResultObjectProviders, Datacache Plug-in]
WARN [main] (LicenseChecker.java:181) - WARNING: Kodo JDO Evaluation
expires in 8 days. Please contact [email protected] for
information on extending your evaluation period or purchasing a
license.
WARN [main] (LicenseChecker.java:181) - WARNING: Kodo JDO Evaluation
expires in 8 days. Please contact [email protected] for
information on extending your evaluation period or purchasing alicense.
DEBUG [main] (JDBCPersistenceManagerFactory.java:444) -
[email protected]b9:
registering 1 classes: [class reachability.AttributeType]
DEBUG [main] (JDBCPersistenceManagerFactory.java:444) -
[email protected]b9:
registering 1 classes: [class reachability.AttributeType]
DEBUG [main] (MetaDataParser.java:136) - found JDO resource
package.jdo for reachability.AttributeType at
file:/F:/Sources/Projects/Bugs/jdo/kodo/reachability/package.jdo
DEBUG [main] (MetaDataParser.java:136) - found JDO resource
package.jdo for reachability.AttributeType at
file:/F:/Sources/Projects/Bugs/jdo/kodo/reachability/package.jdo
INFO [main] (JDOMetaDataParser.java:89) -
com.solarmetric.kodo.meta.JDOMetaDataParser@3020ad: parsing source:
file:/F:/Sources/Projects/Bugs/jdo/kodo/reachability/package.jdo
INFO [main] (JDOMetaDataParser.java:89) -
com.solarmetric.kodo.meta.JDOMetaDataParser@3020ad: parsing source:
file:/F:/Sources/Projects/Bugs/jdo/kodo/reachability/package.jdo
DEBUG [main] (MetaDataParser.java:204) - parsed
file:/F:/Sources/Projects/Bugs/jdo/kodo/reachability/package.jdo:
[com.solarmetric.kodo.meta.ClassMetaData@2200d5[;type=class
reachability.Attribute;loader=sun.misc.Launcher$AppClassLoader@12f6684;finis
hed=false;enhanced=false],
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=false;enhanced=true]]
>>>
DEBUG [main] (MetaDataParser.java:204) - parsed
file:/F:/Sources/Projects/Bugs/jdo/kodo/reachability/package.jdo:
[com.solarmetric.kodo.meta.ClassMetaData@2200d5[;type=class
reachability.Attribute;loader=sun.misc.Launcher$AppClassLoader@12f6684;finis
hed=false;enhanced=false],
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=false;enhanced=true]]
>>>
DEBUG [main] (ClassMetaData.java:305) - parsed metadata: type=class
reachability.AttributeType@110003;validate=true:
[com.solarmetric.kodo.meta.ClassMetaData@2200d5[;type=class
reachability.Attribute;loader=sun.misc.Launcher$AppClassLoader@12f6684;finis
hed=false;enhanced=false],
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=false;enhanced=true]]
>>>
DEBUG [main] (ClassMetaData.java:305) - parsed metadata: type=class
reachability.AttributeType@110003;validate=true:
[com.solarmetric.kodo.meta.ClassMetaData@2200d5[;type=class
reachability.Attribute;loader=sun.misc.Launcher$AppClassLoader@12f6684;finis
hed=false;enhanced=false],
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=false;enhanced=true]]
>>>
DEBUG [main] (ClassMetaData.java:327) - cached metadata:
type=reachability.Attribute@49d67c;loader=com.solarmetric.kodo.util.MultiLoa
derClassResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
com.solarmetric.kodo.meta.ClassMetaData@2200d5[;type=class
reachability.Attribute;loader=sun.misc.Launcher$AppClassLoader@12f6684;finis
hed=false;enhanced=false]
>>>
DEBUG [main] (ClassMetaData.java:327) - cached metadata:
type=reachability.Attribute@49d67c;loader=com.solarmetric.kodo.util.MultiLoa
derClassResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
com.solarmetric.kodo.meta.ClassMetaData@2200d5[;type=class
reachability.Attribute;loader=sun.misc.Launcher$AppClassLoader@12f6684;finis
hed=false;enhanced=false]
>>>
DEBUG [main] (ClassMetaData.java:327) - cached metadata:
type=reachability.AttributeType@110003;loader=com.solarmetric.kodo.util.Mult
iLoaderClassResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=false;enhanced=true]
>>>
DEBUG [main] (ClassMetaData.java:327) - cached metadata:
type=reachability.AttributeType@110003;loader=com.solarmetric.kodo.util.Mult
iLoaderClassResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=false;enhanced=true]
>>>
DEBUG [main] (ClassMetaData.java:305) - parsed metadata: type=class
java.lang.Object@16fd0b7;validate=true: []
DEBUG [main] (ClassMetaData.java:305) - parsed metadata: type=class
java.lang.Object@16fd0b7;validate=true: []
DEBUG [main] (ClassMetaData.java:344) - created metadata:
type=java.lang.Object@16fd0b7;loader=com.solarmetric.kodo.util.MultiLoaderCl
assResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
null
DEBUG [main] (ClassMetaData.java:344) - created metadata:
type=java.lang.Object@16fd0b7;loader=com.solarmetric.kodo.util.MultiLoaderCl
assResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
null
DEBUG [main] (ClassMetaData.java:344) - created metadata:
type=reachability.AttributeType@110003;loader=com.solarmetric.kodo.util.Mult
iLoaderClassResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=true;enhanced=true]
>>>
DEBUG [main] (ClassMetaData.java:344) - created metadata:
type=reachability.AttributeType@110003;loader=com.solarmetric.kodo.util.Mult
iLoaderClassResolver@12f66a3
loaders: [sun.misc.Launcher$AppClassLoader@12f6684]; thread's context
class loader: sun.misc.Launcher$AppClassLoader@12f6684;validate=true:
com.solarmetric.kodo.meta.ClassMetaData@64ab4d[;type=class
reachability.AttributeType;loader=sun.misc.Launcher$AppClassLoader@12f6684;f
inished=true;enhanced=true]
>>>
DEBUG [main] (DataSourceImpl.java:323) - [ C:5896993; T:24537094;
D:10973446 ] open: jdbc:oracle:thin:@SUNFIRE:1521:CCLDEV (CCLJDO)
DEBUG [main] (DataSourceImpl.java:323) - [ C:5896993; T:24537094;
D:10973446 ] open: jdbc:oracle:thin:@SUNFIRE:1521:CCLDEV (CCLJDO)
DEBUG [main] (DataSourceImpl.java:323) - [ C:5896993; T:24537094;
D:10973446 ] close:
com.solarmetric.datasource.PoolConnection@59fb21[identityHashCode:8499707,wr
apped:com.solarmetric.datasource.PreparedStatementCache$CacheAwareConnection
@59fb21[identityHashCode:13359904,wrapped:oracle.jdbc.driver.OracleConnectio
n@59fb21]:
>>>
[requests=0;size=0;max=70;hits=0;created=0;redundant=0;overflow=0;new=0;leak
ed=0;unavailable=0]]
>>>
DEBUG [main] (DataSourceImpl.java:323) - [ C:5896993; T:24537094;
D:10973446 ] close:
com.solarmetric.datasource.PoolConnection@59fb21[identityHashCode:8499707,wr
apped:com.solarmetric.datasource.PreparedStatementCache$CacheAwareConnection
@59fb21[identityHashCode:13359904,wrapped:oracle.jdbc.driver.OracleConnectio
n@59fb21]:
>>>
[requests=0;size=0;max=70;hits=0;created=0;redundant=0;overflow=0;new=0;leak
ed=0;unavailable=0]]
>>>
DEBUG [main] (DataSourceImpl.java:323) - [ C:5896993; T:24537094;
D:10973446 ] close connection
DEBUG [main] (DataSourceImpl.java:323) - [ C:5896993; T:24537094;
D:10973446 ] close connection
INFO [main] (DBDictionaryFactory.java:402) - Using dictionary class
"com.solarmetric.kodo.impl.jdbc.schema.dict.OracleDictionary" to
connect to "Oracle" (version "Oracle8i Enterprise Edition Release
8.1.7.0.0 - 64bit Production
With the Partitioning option
JServer Release 8.1.7.0.0 - 64bit Production") with JDBC driver
"Oracle JDBC driver" (version "9.2.0.1.0")
INFO [main] (DBDictionaryFactory.java:402) - Using dictionary class
"com.solarmetric.kodo.impl.jdbc.schema.dict.OracleDictionary" to
connect to "Oracle" (version "Oracle8i Enterprise Edition Release
8.1.7.0.0 - 64bit Production
With the Partitioning option
JServer Release 8.1.7.0.0 - 64bit Production") with JDBC driver
"Oracle JDBC driver" (version "9.2.0.1.0")
DEBUG [main] (JDBCPersistenceManagerFactory.java:345) -
[email protected]b9:
registerClass: reachability.AttributeType@110003=>true
DEBUG [main] (JDBCPersistenceManagerFactory.java:345) -
[email protected]b9:
registerClass: reachability.AttributeType@110003=>true
DEBUG [main] (JDBCPersistenceManagerFactory.java:444) -
[email protected]b9:
registering 2 classes: [class reachability.AttributeType, class
reachability.Attribute]
DEBUG [main] (JDBCPersistenceManagerFactory.java:444) -
[email protected]b9:
registering 2 classes: [class reachability.AttributeType, class
reachability.Attribute]
DEBUG [main] (JDBCPersistenceManagerFactory.java:345) -
[email protected]b9:
registerClass: reachability.Attribute@49d67c=>true
DEBUG [main] (JDBCPersistenceManagerFactory.java:345) -
[email protected]b9:
registerClass: reachability.Attribute@49d67c=>true
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] open: jdbc:oracle:thin:@SUNFIRE:1521:CCLDEV (CCLJDO)
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] open: jdbc:oracle:thin:@SUNFIRE:1521:CCLDEV (CCLJDO)
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] preparing statement <11544872>: SELECT SYSDATE FROM DUAL
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] preparing statement <11544872>: SELECT SYSDATE FROM DUAL
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] executing statement <11544872>: (SELECT SYSDATE FROM
DUAL): [reused=1;params={}]
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] executing statement <11544872>: (SELECT SYSDATE FROM
DUAL): [reused=1;params={}]
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] preparing statement <24880015>: INSERT INTO
ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] preparing statement <24880015>: INSERT INTO
ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] executing statement <24880015>: (INSERT INTO
ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)):
[reused=1;params={(int)10,(int)10,(String)KODO}]
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] executing statement <24880015>: (INSERT INTO
ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)):
[reused=1;params={(int)10,(int)10,(String)KODO}]
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] begin rollback
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] begin rollback
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] end rollback 0ms
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] end rollback 0ms
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] close:
com.solarmetric.datasource.PoolConnection@69d02b[identityHashCode:6151022,wr
apped:com.solarmetric.datasource.PreparedStatementCache$CacheAwareConnection
@69d02b[identityHashCode:32580443,wrapped:oracle.jdbc.driver.OracleConnectio
n@69d02b]:
>>>
[requests=2;size=2;max=70;hits=0;created=2;redundant=0;overflow=0;new=2;leak
ed=0;unavailable=0]]
>>>
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] close:
com.solarmetric.datasource.PoolConnection@69d02b[identityHashCode:6151022,wr
apped:com.solarmetric.datasource.PreparedStatementCache$CacheAwareConnection
@69d02b[identityHashCode:32580443,wrapped:oracle.jdbc.driver.OracleConnectio
n@69d02b]:
>>>
[requests=2;size=2;max=70;hits=0;created=2;redundant=0;overflow=0;new=2;leak
ed=0;unavailable=0]]
>>>
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] close connection
DEBUG [main] (DataSourceImpl.java:323) - [ C:6934571; T:24537094;
D:10973446 ] close connection
DEBUG [main] (PersistenceManagerImpl.java:481) - An exception occurred
while ending a transaction. This exception will be thrown. It is being
logged here for informational purposes only.
com.solarmetric.kodo.runtime.FatalDataStoreException:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT
INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (10, 10, 'KODO')]
[PRE=INSERT INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)]
ORA-02291: integrity constraint (CCLJDO.ATTRIBUTE_FK) violated -
parent key not found
[code=2291;state=23000]
NestedThrowables:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT
INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (10, 10, 'KODO')]
[PRE=INSERT INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)]
ORA-02291: integrity constraint (CCLJDO.ATTRIBUTE_FK) violated -
parent key not found
at
com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwFatal(SQLException
s.java:58)
>>>
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManag
er.java:559)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flushInternal(Persistenc
eManagerImpl.java:697)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManage
rImpl.java:422)
>>>
at
reachabilicom.solarmetric.kodo.runtime.FatalDataStoreException:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT
INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (10, 10, 'KODO')]
[PRE=INSERT INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?,
ty.Main.main(Main.java:26)
NestedThrowablesStackTrace:
java.sql.SQLException: ORA-02291: integrity constraint
(CCLJDO.ATTRIBUTE_FK) violated - parent key not found
at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
atoracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1891)> >> at> >> oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)> >> at> >>oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047)> >>> >> at> >>oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)> >>> >> at> >>oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2709)> >>> >> at> >>oracle.jdbc.driver.OraclePreparedStatement.doScrollPstmtExecuteUpdate(OraclePreparedStatement.java:3975)> >>> >> at> >>oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:623)> >>> >> at> >>com.solarmetric.datasource.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:111)> >>> >> at> >>com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatementNonBatch(SQLExecutionManagerImpl.java:454)> >>> >> at> >>com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatement(SQLExecutio?,> >> ?)
ORA-02291: integrity constraint (CCLJDO.ATTRIBUTE_FK) violated -
parent key not found
[code=2291;state=23000]
NestedThrowables:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT
INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (nManagerImpl.java:423)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executeInternal(SQLEx
ecutionManagerImpl.java:381)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.flush(SQLExecutionMan
agerImpl.java:255)
>>>
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManag
er.java:554)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flushInternal(Persistenc
eManagerImpl.java:697)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManage
rImpl.java:422)
>>>
at reachability.Main.main(Main.java:26)
DEBUG [main] (PersistenceManagerImpl.java:481) - An exception occurred
while ending a transaction. This exception will be thrown. It is being
logged here for informational purposes only.
com.solar10, 10, 'KODO')] [PRE=INSERT INTO ATTRIBUTE(CLASS_ID,
TYPE_ID, VALUE) VALUES (?, ?, ?)]
ORA-02291: integrity constraint (CCLJDO.ATTRIBUTE_FK) violated -
parent key not found
at
com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwFatal(SQLExceptmet
ric.kodo.runtime.FatalDataStoreException:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT
INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (10, 10, 'KODO')]
[PRE=INSERT INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)]
ORA-02291: integrity constraint (CCLJDO.ATTRIBUTE_FK) violated -
parent key not found
[code=2291;state=23000]
NestedThrowables:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT
INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (10, 10, 'KODO')]
[PRE=INSERT INTO ATTRIBUTE(CLASS_ID, TYPE_ID, VALUE) VALUES (?, ?, ?)]
ORA-02291: integrity constraint (CCLJDO.ATTRIBUTE_FK) violated -
parent key not found
at
com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwFatal(SQLException
s.java:58)
>>>
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManag
er.java:559)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flushInternal(Persistenc
eManagerImpl.java:697)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManage
rImpl.java:422)
>>>
at reachability.Main.main(Main.java:26)
NestedThrowablesStackTrace:
java.sql.SQLException: ORA-02291: integrity constraint
(CCLJDO.ATTRIBUTE_FK) violated - parent key not found
at oracle.jdbc.dbaccess.DBErions.java:58)
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManag
er.java:559)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flushInternal(Persistenc
eManagerImpl.java:697)
>>>
at
com.solarmetric.kodo.runtime.Persistencror.throwSqlException(DBError.java:13
4)
>>>
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
atoracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1891)
at
oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
at
oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047
>>>
at
oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
>>>
at
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java
:2709)
>>>
at
oracle.jdbc.driver.OraclePreparedStatement.doScrollPstmtExecuteUpdate(Oracle
PreparedStatement.java:3975)
>>>
at
oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedState
ment.java:623)
>>>
at
com.solarmetric.datasource.PreparedStatementWrapper.executeUpdate(PreparedSt
atementWrapper.java:111)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatem
entNonBatch(SQLExecutionManagerImpl.java:454)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatem
ent(SQLExecutionManagerImpl.java:423)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executeInternal(SQLEx
ecutionManagerImpl.java:381)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.flush(SQLExecutionMan
agerImpl.java:255)
>>>
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManag
er.java:554)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flushInternal(Persistenc
eManagerImpl.java:697)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManage
rImpl.java:422)
>>>
at reachability.Main.main(Main.java:26)
eManagerImpl.commit(PersistenceManagerImpl.java:422)
at reachability.Main.main(Main.java:26)
NestedThrowablesStackTrace:
java.sql.SQLException: ORA-02291: integrity constraint
(CCLJDO.ATTRIBUTE_FK) violated - parent key not found
at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
atoracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1891)
at
oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
at
oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047
>>>
at
oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
>>>
at
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java
:2709)
>>>
at
oracle.jdbc.driver.OraclePreparedStatement.doScrollPstmtExecuteUpdate(Oracle
PreparedStatement.java:3975)
>>>
at
oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedState
ment.java:623)
>>>
at
com.solarmetric.datasource.PreparedStatementWrapper.executeUpdate(PreparedSt
atementWrapper.java:111)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatem
entNonBatch(SQLExecutionManagerImpl.java:454)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatem
ent(SQLExecutionManagerImpl.java:423)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executeInternal(SQLEx
ecutionManagerImpl.java:381)
>>>
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.flush(SQLExecutionMan
agerImpl.java:255)
>>>
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManag
er.java:554)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flushInternal(Persistenc
eManagerImpl.java:697)
>>>
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManage
rImpl.java:422)
>>>
at reachability.Main.main(Main.java:26)
Exception in thread "main" _ -
Creating a persistent check box in a Content Editor Web Part
I'm using the following HTML in a Content Editor Web Part to display a check box. It works great, but how can I make the checkbox state persistent? (i.e, it remembers whether it is checked or not between sessions).
HTML: <input name="Completed" type="checkbox" value="Completed" />Hi
Adoukusa ,
For creating a persistent check box in a Content Editor Web Part, you need to use cookie to store the state of the checkbox and maintain the state by reading / writing cookies.
Here is JavaScript cookie sample code:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
return null;
function eraseCookie(name) {
createCookie(name,"",-1);
Reference:
http://stackoverflow.com/questions/1154258/persistence-of-checkbox-values
Best Regards,
Eric
Eric Tao
TechNet Community Support -
Using calculated properties of an entity
Hi all,
I am having some serious trouble in finding out how this works. Maybe I'm not Googling correctly, but I have spent many hours already on this problem and I'm not getting anywhere. I am also reasonably sure I have checked out all the Netbeans tutorials on this matter, but alas. So I guess, I could do with some help.
This is really a basic (beginner?) question about persistence. As a side note: I am using Netbeans 6.7
I am running a database and all my tables have corresponding entity classes. I have a GUI in which I want to display a table from the database, together with some calculated values.
I'll make the setup as simple as possible. Take the simple database created by
CREATE DATABASE administration;
USE administration;
CREATE TABLE customers (
id INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(50) NOT NULL,
surname VARCHAR(50 NOT NULL,
PRIMARY KEY(id)
) ENGINE=INNODB;
INSERT INTO customers (firstname, surname)
VALUES ('John', 'Adams'), ('Caroline', 'Nixon')Based on this database, Netbeans creates an entity class
@Entity
@Table(name = "customers")
@NamedQueries({
@NamedQuery(name = "Customers.findAll", query = "SELECT c FROM Customers c"),
@NamedQuery(name = "Customers.findById", query = "SELECT c FROM Customers c WHERE c.id = :id"),
@NamedQuery(name = "Customers.findByFirstname", query = "SELECT c FROM Customers c WHERE c.firstname= :firstname"),
@NamedQuery(name = "Customers.findBySurname", query = "SELECT c FROM Customers c WHERE c.surname= :surname")})
public class Customers implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "firstname")
private String firstname;
@Basic(optional = false)
@Column(name = "surname")
private String surname;
// CONSTRUCTORS
// GET AND SET METHODS
// A FEW SIMPLE @override METHODS
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
} public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}Now, using the Netbeans GUI tools I create a JTable with values bound to Customers. This works fine: the apllication reads the database and displays correct values in the table (however, externally making a change in the database is not updated in the table, nor are changes in the table sent to the database, but that is a different matter - gonna work on that after this).
The next step is creating a calculated property, say "private String adressee" which is calculated by Java code the be for example "C. Nixon" or "J. Adams". (*This is my question: what is the correct way of implementing something like this, so that it is updated in the table when firstname or surname are altered*?) Now the problems start. Simply defining this property gives errors, because it is automatically interpreted as a persistent value. So the apllication does an SQL query interpreting 'adressee' as a column, which of course results in an error. Alternatively, I can define 'adressee' as @Transient. Now, the application compiles and runs, but 'adressee' is never updated in the table. Note that I update it manually: that is, I have the program listen to PropertyChange for surname and firstname, and the generate the correct value for adressee. This works, but is not reflected in the table. I have also tried to refresh() the JTableBinding when a PropertyChange occurs, but this returns a NullPointerException. Moreover, even if that should work, I am convinced there must be a way more elegant method.
I anyone would be so kind as to enlighten me, please do!
GreetsSomehow, retrying my first technique worked. Maybe it is because I am now using Hobernate, set to Eager (not Lazy, which gave me compiling errors!). For future reference, here is how I did it.
The MySQL table is called 'relaties'. 'contactpersoon' is a value which I want to calculate from several other values from this table and its related tables.
I use Netbeans to create entity classes from database. One of which is Relaties:
@Entity
@Table(name = "relaties", catalog = "TK", schema = "")
public class Relaties implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
// AND MANY OTHER COLUMNS, THE USUAL ENTITY CODE
@Transient
private String contactpersoon;
public String getContactpersoon() {
return contactpersoon;
public void setContactpersoon(String contactpersoon) {
String oldContactpersoon = this.contactpersoon;
this.contactpersoon = contactpersoon;
changeSupport.firePropertyChange("contactpersoon", oldContactpersoon, contactpersoon);
public void genContactpersoon() {
// calculation code - note that I had to catch NullPointerExceptions for Columns without @Basic(optional = false)
this.setContactpersoon(s);
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}I now make another class, in which I put everything I think Relaties should do itself, but I can't put in there because of compilation errors (my bad?):
public class RelatiesHelper implements PropertyChangeListener {
public void init(Relaties r) {
r.addPropertyChangeListener(this);
r.genContactpersoon();
r.genAdressering();
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("achternaam") || evt.getPropertyName().equals("tussenvoegsels") || evt.getPropertyName().equals("voornaam") || evt.getPropertyName().equals("titel")) { // these are column titles of the properties on which 'contactpersoon' depends
((Relaties) evt.getSource()).genContactpersoon();
}I now made a class ViewRelaties, which includes a JTable. The values of this JTable can now be bound in the usual way, including 'contactpersoon':
public class ViewRelaties
extends javax.swing.JPanel {
/** Creates new form ViewRelaties */
public ViewRelaties() {
initComponents(); // code to create table and initialize a Relaties-list, bind values etc.
ListIterator<Relaties> l = this.relatiesList.listIterator();
RelatiesHelper rh = new RelatiesHelper();
while (l.hasNext()) {
rh.init(l.next());
// THE initComponents() CODE
private javax.persistence.EntityManager AdminPUEntityManager;
private javax.persistence.Query relatiesQuery;
private java.util.List<admin.entities.Relaties> relatiesList;
}Hope this helps someone :)
Edited by: Quinten1 on Aug 1, 2009 5:21 AM -
Noob Question: Problem with Persistence in First Entity Bean
Hey folks,
I have started with EJB3 just recently. After reading several books on the topic I finally started programming myself. I wanted to develop a little application for getting a feeling of the technology. So what I did is to create a AppClient, which calls a Stateless Session Bean. This Stateless Bean then adds an Entity to the Database. For doing this I use Netbeans 6.5 and the integrated glassfish. The problem I am facing is, that the mapping somehow doesnt work, but I have no clue why it doesn't work. I just get an EJBException.
I would be very thankfull if you guys could help me out of this. And don't forget this is my first ejb project - i might need a very detailed answer ... I know - noobs can be a real ....
So here is the code of the application. I have a few methods to do some extra work there, you can ignore them, there are of no use at the moment. All that is really implemented is testConnection() and testAddCompany(). The testconnection() Methode works pretty fine, but when it comes to the testAddCompany I get into problems.
Edit:As I found out just now, there is the possibility of Netbeans to add a Facade pattern to an Entity bean. If I use this, everythings fine and it works out to be perfect, however I am still curious, why the approach without the given classes by netbeans it doesn't work.
public class Main {
private EntryRemote entryPoint = null;
public static void main(String[] args) throws NamingException {
Main main = new Main();
main.runApplication();
private void runApplication()throws NamingException{
this.getContext();
this.testConnection();
this.testAddCompany();
this.testAddShipmentAddress(1);
this.testAddBillingAddress(1);
this.testAddEmployee(1);
this.addBankAccount(1);
private void getContext() throws NamingException{
InitialContext ctx = new InitialContext();
this.entryPoint = (EntryRemote) ctx.lookup("Entry#ejb.EntryRemote");
private void testConnection()
System.err.println("Can Bean Entry be reached: " + entryPoint.isAlive());
private void testAddCompany(){
Company company = new Company();
company.setName("JavaFreaks");
entryPoint.addCompany(company);
System.err.println("JavaFreaks has been placed in the db");
}Here is the Stateless Session Bean. I added the PersistenceContext, and its also mapped in the persistence.xml file, however here the trouble starts.
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless(mappedName="Entry")
public class EntryBean implements EntryRemote {
@PersistenceContext(unitName="PersistenceUnit") private EntityManager manager;
public boolean isAlive() {
return true;
public boolean addCompany(Company company) {
manager.persist(company);
return true;
public boolean addShipmentAddress(long companyId) {
return false;
public boolean addBillingAddress(long companyId) {
return false;
public boolean addEmployee(long companyId) {
return false;
public boolean addBankAccount(long companyId) {
return false;
}That you guys and gals will have a complete overview of whats really going on, here is the Entity as well.
package ejb;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name="COMPANY")
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="COMPANY_NAME")
private String name;
public Long getId() {
return id;
public void setId(Long id) {
this.id = id;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
System.err.println("SUCCESS: CompanyName SET");
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Company)) {
return false;
Company other = (Company) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
return true;
@Override
public String toString() {
return "ejb.Company[id=" + id + "]";
}And the persistence.xml file
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="PersistenceUnit" transaction-type="JTA">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="toplink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>And this is the error message
08.06.2009 10:30:46 com.sun.enterprise.appclient.MainWithModuleSupport <init>
WARNUNG: ACC003: Ausnahmefehler bei Anwendung.
javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:243)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:205)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:152)
at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(BCELStubBase.java:225)
at ejb.__EntryRemote_Remote_DynamicStub.addCompany(ejb/__EntryRemote_Remote_DynamicStub.java)I spend half the night figuring out whats wrong, however I couldnt find any solution.
If you have any idea pls let me know
Best regards and happy coding
Taggert
Edited by: Taggert_77 on Jun 8, 2009 2:27 PMWell I don't understand this. If Netbeans created a Stateless Session Bean as a facade then it works -and it is implemented as a CMP, not as a BMP as you suggested.
I defenitely will try you suggestion, just for curiosity and to learn the technology, however I dont have see why BMP will work and CMP won't.
I also don't see why a stateless bean can not be a CMP. As far as I read it should not matter. Also on the link you sent me, I can't see anything related to that.
Maybe you can help me answering these questions.
I hope the above lines don't sound harsh. I really appreciate your input.
Best regards
Taggert -
Newbie question on Java Persistence API - Entity Beans
Hi All,
I am basically new to Entities and the Java Persistence API. My question is, when using a container managed EntityManager, do I have to manually tidy-up any resources? Say for example, do I have to explicitly close the database connection (if ever I have that ability)? Invoke close() on EntityManager?
- PatYou don't have to. That's what they mean by container managed. The container does it for you.
In fact you will get an IllegalStateException if you call close on a container-managed EntityManager. -
Persistence API newbie question
Hello everybody!
I am new at J2EE development, so can you explain me some details. We're curently do J2EE application at work and using J2EE 1.5 features(EJB 3.0, Persistence etc..). I don't understand exactly what lies under annotations. Let's take Persistence API. All anotations and classes is in javax.persistence package. What is that package, where it come from? Is it located in container or where? In fact I would like to use Persistence API on sites managed by Apache Tomcat Server. Is it possible, what classes do I need? Another question is it is possible to use that API at Swing Applications, and what do I need to do this.
Please, explain me little of where all that stuff come from.
Thank you!anotations and classes is in javax.persistence
package. What is that package, where it come from? Is
it located in container or where? Java Persistence API (JPA) is part of JavaEE 5 platform, and so is available in all JavaEE 5 compliant application servers. In JavaEE SDK 5, these classes are in lib/javaee.jar. JPA is also available as a standalone technology. There are several products that are implementing this technology, like Hibernate, TopLink, or OpenJPA.
The specification:
http://jcp.org/en/jsr/detail?id=220
Persistence Part in JavaEE 5 Tutorial (Part Four: Persistence )
http://java.sun.com/javaee/5/docs/tutorial/doc/
In fact I would
like to use Persistence API on sites managed by
Apache Tomcat Server. Is it possible, what classes do
I need? Another question is it is possible to use
that API at Swing Applications, and what do I need to
do this. They are all possible ways of using JPA. See JavaEE 5 Tutorial for more details. The newly released NetBeans 5.5 has nice support for developing and deploying JPA applications. NetBeans site has a lot of resources on this topic. For example:
http://www.netbeans.org/kb/55/persistence_ontomcat.html
http://www.netbeans.org/kb/articles/hibernate-javaee.html
-cheng -
Hi,
I am very new to JDO and Kodo and I am still learning. I have a user
specification that requires no data loss when the application crashes. If I
am developing my application using Kodo for data access layer, when my
application crashes just because and needs to restart, what happen to all
the persistence data that have not committed to database??
VivianI am very new to JDO and Kodo and I am still learning. I have a user
specification that requires no data loss when the application crashes.
If I am developing my application using Kodo for data access layer, when
my application crashes just because and needs to restart, what happen to
all the persistence data that have not committed to database??If an app crashes, all current transactions will be aborted. There is a
difference between data loss and aborting the current transaction. Data
loss implies losing some persistent data -- data that resides in the
database. That won't happen with Kodo.
You will, however, lose any changes that have not been committed to the
database yet. This is a good thing. You absolutely DO NOT want an
unfinished transaction to be recorded, because that could violate the
integrity of your data. Consider a transaction that decrements from one
bank account and increments another to implement a funds transfer. You
certainly wouldn't want to record the decrement unless you are absolutely
sure the increment would be recorded too! -
Question on Using Persistence Object
Hi,
I want to store a hashtable of persistent info with about five attributes (id, name, username, date) in order to not always call the database. I am either going to use session or request objects.
My question is if it's a good idea to store the hashtable with 2000 records just to avoid the database connection or should I just stick with using database connection using connection pooling? Thanks.
MkieHow long you are going to store it ????
1. If it is for a long time then this is not a good strategy as:
a) Database data can change (in that case you will have wrong data)
b) Your heap memory will be unnecessarily loaded.
2. If it is for a very short time then it again carries no meaning as creating the object will have a significant overhead.
3) If it is something between these two. You need to have a thorough analysis to see which would be best. However in my humble opinion a scrollable resultset(JDBC 2.0) will still be better.
Shubhrajit -
Question about Java Persistence API.
is Java Persistence API a Object-Relational Mapping Framework, or the java Programmer can use this API to do mapping between Java Applicatiion and Relational Database ??
http://java.sun.com/javaee/overview/faq/persistence.jsp
-
Hi,
I am attempting to write something like a text game in Java. Obviously for something like this I need to be able to save the state of the program, so I am attempting to use persistence but I am running into a problem. My Game object contains everything to do with the game and I have a StartGame object that performs the saving and loading and calls game object to run.
I can successfully save and load the game object using File and Object Output/InputStreams but upon loading the Game object no longer has any of the objects it is supposed to have saved. For example, there is a currentRoom pointer that points to an object of type Room (a custom class). I want this (and many other pointers like it) to have their referenced objects saved and still be pointing to them when a file is loaded. Can anyone enlighten me as to why this is not working?
I guess the alternative might be to save each and every object within Game individually, but from what I have read it seems like it's supposed to be simpler than that. Thanks for any help.I realized I made a silly mistake and was writing the wrong file name originally, but now I have another problem in that it will not even write the game object to the ObjectOutputStream.
This is the class that runs the game:
import java.io.*;
public class StartGame2
static Game game;
static boolean runOnce = true;
public static void main(String args[])
game = new Game();
while(!game.exit)
game.load = false;
game.save = false;
game.runGame();
if(game.save)
save(game.saveName);
if(game.load)
load(game.loadName);
System.exit(0);
static void save(String saveName)
try
// Create a file to write game system
FileOutputStream out = new FileOutputStream (saveName);
// Create an object output stream, linked to out
ObjectOutputStream objectOut = new ObjectOutputStream (out);
// Write game to disk
objectOut.writeObject (game);
// Close object output stream
objectOut.close();
Game.print("Game saved as " + saveName);
catch (Exception e)
System.err.println ("Unable to create game data");
static void load(String loadName)
FileInputStream fin = null;
ObjectInputStream objectIn = null;
try
// Create a file input stream
fin = new FileInputStream(loadName);
// Create an object input stream
objectIn = new ObjectInputStream(fin);
// Read an object in from object store, and cast it to a game
game = (Game) objectIn.readObject();
catch (Exception e)
Game.print("Failed to load.");
}//End startGameThe Game class itself is of the form:
public class Game implements Serializable
public void runGame()
//These should only run once
if(StartGame2.runOnce)
welcome();
makeRooms();
makePeople();
if(!exit && !load)
intro();
StartGame2.runOnce = false;
while(!exit && !load && !save)
...doStuff...
}Edited by: DrSpock11 on Mar 2, 2009 11:06 AM -
General Persistence Implementation Strategy Question
Hi,
I want to implement a J2EE application and use a persistence system like Hibernate. I will have to create several beans and set-up my ORM properly. Now, if I create an Enterprise project in NetBeans, where should I put my Peristence code? In a Web container or in a EBJ container knowing that both JSP pages and EJB will refer to my persisted beans? Or should I create another separate project and include the corresponding .jar in both my Web or EJB containers?
What is the best strategy?
Thanks,
J.Jrm wrote:
Hi,
I want to implement a J2EE application and use a persistence system like Hibernate. I will have to create several beans and set-up my ORM properly. Now, if I create an Enterprise project in NetBeans, where should I put my Peristence code? In a Web container or in a EBJ container +
knowing that both JSP pages and EJB will refer to my persisted beans+? I would say that JSPs should not be contacting your database directly. Better to go through a well-defined service layer that hides the persistence layer. All security, binding, and validation issues should be resolved before the service layer is called.
Or should I create another separate project and include the corresponding .jar in both my Web or EJB containers?Both? Wrong.
% -
Persistence Layer return convention issue and question - null vs. exception
I'm writing a position paper on persistence layer query returns. It deals with querying for a single object or a collection of objects and what to do if the object or collection of objects are not found in the database. I've googled many different search terms and have not come up with any authoritative references for this scenario. Do any of you know of any sources that have discussed this before?
My current logic is that when searching for a single object in a persistence layer that the persistence layer should return a simple null if the object isn't found. If searching for a collection of objects then the PL should return an empty collection object.
1.
/** Returns a list of objects that match the non-null fields in the provided example object.
This will return an empty Collection if no matching objects are found */
public Collection retrieveByExample(MyBO example);2. /** Returns a business object. This will return a null if no matching object is found */
public MyBusObject retrieveById(int aMyBusObjectId);These two methods would not return a "checked or unchecked" exception if the object(s) are not found. I think that they are the simplest to implement and do not break the convention of not using exceptions in non exceptional situations. I don't feel that it is the persistence layer's responsibility to make a business decision on an object's existence being an exception. There are many times where applications search for an object to see if it exists or not and then proceed to create the object or use the object if it exists or doesn't. These two methods also don't force using application layers to catch or throw any declared exceptions.
Notes on scenario 1: program control flow is simple by using an iterator and hasNext(), if the collection is empty then any code that needs the objects can be skipped.
Notes on scenario 2: program control flow is simple in this case with a " != null or == null check. If the method returned an uninitialized object instead of null then the calling application would have to have additional business logic to tell whether the object was truly uninitialized or not. I can see the method having a UnexpectedMultipleBusinessObjectsFoundException if more than 1 object is found since the method is looking by primary key, but would this ever happen if searching by primary key. However in a similiar method that searches on non primary key then the UMBOFE would be warrented. Any thoughts?
Others have brought up some additional scenarios.
3. /** Returns one and only one business object from persistence with a matching primary id.
If one and only one match is not found, null is returned if isLenient is true, otherwise an exception is thrown. */
public MyBusObject retrieveById(int aMyBusObjectId, boolean isLenient) throws BusinessObjectNotFoundException;I feel this option is bad in that it forces the calling or using application layer to still declare the BusinessObjectNotFoundException. It adds bulk and unneeded complexity to the the code.
While looking at it I can see that since a caller is searching for exactly 1 object then if the query finds more than one object then a UnexpectedMultipleBusinessObjectsFoundException could be thrown. But I don't believe an NotFoundException is warranted. What are your thoughts?
Message was edited by:
smalltalkHibernate (for example) actually does both.
public Object get(Class clazz, Serializable id) throws HibernateException - "Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance, or a proxy for the instance, is already associated with the session, return that instance or proxy.)"
public Object load(Class theClass, Serializable id) throws HibernateException: "Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error."
Certainly get is the more commonly used of these methods.
If you are returning something like an array I believe it is always preferable to return a zero length array rather than null to save the extra client code.
Maybe you are looking for
-
Problem with skype contacts added each time when I sync with my computer
Dear Black Berry, I have a Business edition Black Berry Q10 model phone. The problem is I see duplicates of my skype contacts, day by day its getting worse. Im unable to find a solution for this. Need your help!! How can I stop these contacts duplic
-
Here are some ideas about using some of the IM chat solutions in CRM OD. I have used Google talk and a meebo widget to demonstrate. The HowTo document is on my website HERE Please let me know if you find it useful/interesting
-
I m using smpp protocol to send and receive message ... I want to retreive all the parameter when pdu will send suppose i send submit_sm then i want to retrieve command id ,commandstatus length....all the parameter for this purpose i want to set flag
-
Authorization newly created user
hi experts, can any body explain, what infotype/authorization will be required for newly created user of HCM. Thanks, Waqas You should first go through the [SAP Help|http://help.sap.com/saphelp_erp60_sp/helpdata/EN/48/efa441d54eae5fe10000000a1550b0/f
-
HD Images ( 1920x1080 ) exported from iMovie09?
Hello, I was able to use iMovie HD to export a full HD movie to a sequence of images (every frame) with full resolution (1920x1080). The function seems still available in iMovie09, however, the highest image resolution I can get is 960x540 no matter