CMP 2.0 bean auto-generated primary key WAS 6.1 - java

is it possible to map bean's key field with identity primary key column in DB2?
Sample table:
CREATE TABLE ADDRESS (
ID INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 2147483647
NO CYCLE
CACHE 20
NO ORDER ),
Line1 VARCHAR(255) NOT NULL,
Line2 VARCHAR(255),
City VARCHAR(255) NOT NULL,
Postcode VARCHAR(6) NOT NULL,
Country VARCHAR(50) NOT NULL,
Latitude DOUBLE,
Longitude DOUBLE
)
AUDIT NONE
DATA CAPTURE NONE
CCSID UNICODE;
ejbCreate methods have been tailored NOT TO set ID field, but it gets initialized with default for integer type - 0 so i'm getting DuplicateKeyException on second and following calls to ejbCreate.
What is the best way to implement IDENTITY behavior? I found many examples for JBoss but nothing for WAS.
It was easy with JPA, but CMP 2.0 is a must at this time

Override method ejbPostCreate. You will be able to retrieve the generated ID from there, and update your model and your code in order to avoid duplicate IDs.
For instance, take a look at http://forums.sun.com/thread.jspa?threadID=699131

Related

integer on 4 positions on apache derby

I want the ID for the client to be on 4 positions like "0007" on apache derby but the following request doesn't work:
create table client(id int (5) not null AUTO_INCREMENT primary key, fname varchar(20) not null, lname varchar(20) not null,phnum int(10) not null, email varchar(60) not null ) ;
it throws this exception:
[Exception, Error code 30 000, SQLState 42X01] Erreur de syntaxe : Encountered "(" at line 1, column 28.
how can I make it happen ?
The Derby int has no width. It is soley an integer.
You may use formatting, to use the id as a 4 digit wide string.
Probably you will use your Derby data later in Java thrua a ORM. It is not recomended to use business data as an object id. Let the id an auto-incrementet value to identify your object. You may add another field (like code) to have the client code stored (char(4) with a unique index to avoid duplicates).
(4. Only preview 10.000 clients, that seems a quiet low limit)

JPA serial numbers using a customer ID generation

I get this error when I try to generate serial numbers for ID using a random generator instead of the built-in strategies:
run:
[EL Info]: 2015-03-27 18:22:05.047--ServerSession(1185812646)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2015-03-27 18:22:09.295--ServerSession(1185812646)--file:/C:/Users/Sobhie/Desktop/people/build/classes/_peoplePU login successful
[EL Warning]: 2015-03-27 18:22:09.498--ServerSession(1185812646)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: BLOB/TEXT column 'R' used in key specification without a key length
Error Code: 1170
Call: CREATE TABLE PERSON (R LONGBLOB NOT NULL, FNAME VARCHAR(255), ID BIGINT, LNAME VARCHAR(255), X INTEGER, PRIMARY KEY (R))
Query: DataModifyQuery(sql="CREATE TABLE PERSON (R LONGBLOB NOT NULL, FNAME VARCHAR(255), ID BIGINT, LNAME VARCHAR(255), X INTEGER, PRIMARY KEY (R))")
BUILD SUCCESSFUL (total time: 13 seconds)
You current custom primary key strategy result in primary keys mapped as blobs (so probably a serialized object)).
Out of the box, BLOB or TEXT cannot be used as PRIMARY KEY in mysql as
a) mysql has limit on how many characeters can form part of the index (so whole TEXT content is out of the question),
b) there is no size constraint for TEXT (for example TEXT(512))
To use TEXT as Primary Key, the index length must be declared explicit (so mysql will look only at the first X characters).
CREATE TABLE PERSON (R TEXT NOT NULL, FNAME VARCHAR(255), ..., KEY ix_length_r (R(255)))
If your R values are not unique in the first XX characters it will not work.
But the mysql ix limit lenght, comes down to 255 for unicodecharacters and to 765 for latin-1. So for unicode you are basically as good as using VARCHAR(255) as your primary key.
You mentioned random number generator for your primary keys but they are mapped as blobs. I don't believe having keys longer than 255 chars makes any sense (it is a huge space about 2E462, so more than atoms in the universe!!!), so you should limit yourself to having them as simple varchar.
But most likely you wanted to use simple Long, but you messed up with your mappings. Impossible to say without the code though.

compare values from two tables

I have 2 tables. First one holds the total values of some shopping lists and the second table holds the products in that list. When a shopping list is done the total value is added into the total table together with some informations like the list number(nrList which is some kind of list id) and the number of products on that list nrProducts while the products go into the listproducts table.Lets say there are 3 products tomato,oranges and apples.They will all share the same nrList which,as mentioned before,is something like the list id.
First table totals:
CREATE TABLE IF NOT EXISTS `totals` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nrList` int(11) NOT NULL,
`nrProducts` int(11) DEFAULT NULL,
`total` double NOT NULL,
`data` date DEFAULT NULL,
`ora` time DEFAULT NULL,
`dataora` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Operator` varchar(50) DEFAULT NULL,
`anulat` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
)
Second table listproducts:
CREATE TABLE IF NOT EXISTS `listproducts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nrList` int(11) DEFAULT NULL,
`product` varchar(50) DEFAULT NULL,
`quantity` double DEFAULT NULL,
`price` double DEFAULT NULL,
`data` date DEFAULT NULL,
`operator` varchar(50) NOT NULL,
`anulat` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
Now,i have two things i want to do,they are very similar.
Lets say i have a list with 3 products.In the totals table there will be a row with some info and with the total=10$ nrProducts=3 and nrList=1.In the listproducts table i will have 3 rows all having nrList=1 and each having price=3$,3$,4$.
Now,i want the check the following :
1.That if the value of nrProducts=3 then i have products for that list in the other table.
2.Check if the total in the first table is equal to the sum of the products in the second table.(quantity*price SUM)
I've done some stuff but i don't know what to do next.
I managed to get the number of products for each list from the second table by using this:
SELECT nrList,operator,COUNT(*) as count FROM listproducts GROUP BY nrList
But i don't know how to compare if the values are equal without doing two queries.
For the second thing again, I know how to get the sum but i don't know how to compare them without doing two separate queries.
SELECT SUM(price*quantity) FROM `listproducts` WHERE nrList='10' and operator like '%x%'
I can also do something like what i've done in the other select,this is not the issue.
The issue is that i don't know how to do the things i want in a single select instead of doing two and comparing them.I'm doing this in java so i can compare but i'd like to know if and how i can do this in a single query.
Thanks and sorry for the long post.
You can try something like this:
SELECT totals.nrList,
IF (totals.nrProducts = t.nrProductsActual, 'yes', 'no') AS matchNrProducts,
IF (totals.total = t.totalActual, 'yes', 'no') AS matchTotal
FROM totals INNER JOIN
(SELECT nrList,
COUNT(*) AS nrProductsActual,
SUM(quantity*price) AS totalActual
FROM listproducts
GROUP BY nrList) AS t ON totals.nrList = t.nrList

INSERT with DEFAULT id doesn't work in PostgreSQL

I tried running this statement in Postgres:
insert into field (id, name) values (DEFAULT, 'Me')
and I got this error:
ERROR: null value in column "id" violates not-null constraint
I ended up having to manually set the id. The problem with that is when my app inserts a record I get a duplicate key error. I am building a java app using Play framework and ebean ORM. So the entire schema is generated automatically by ebean. In this case, what is the best practice for inserting a record manually into my db?
Edit:
Here is how I'm creating my Field class
#Entity
public class Field {
#id
public Long id;
public String name;
}
Edit:
I checked the field_seq sequence and it looks like this:
CREATE SEQUENCE public.field_seq INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1;
Edit:
Here is the generated SQL in pgAdmin III:
CREATE TABLE field
(
id bigint NOT NULL,
created timestamp without time zone,
modified timestamp without time zone,
name character varying(255),
enabled boolean,
auto_set boolean,
section character varying(17),
input_type character varying(8),
user_id bigint,
CONSTRAINT pk_field PRIMARY KEY (id),
CONSTRAINT fk_field_user_3 FOREIGN KEY (user_id)
REFERENCES account (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT ck_field_input_type CHECK (input_type::text = ANY (ARRAY['TEXT'::character varying, 'TEXTAREA'::character varying]::text[])),
CONSTRAINT ck_field_section CHECK (section::text = ANY (ARRAY['MAIN_CONTACT_INFO'::character varying, 'PARTICIPANT_INFO'::character varying]::text[]))
);
CREATE INDEX ix_field_user_3
ON field
USING btree
(user_id);
There is no column default defined for field.id. Since the sequence public.field_seq seems to exist already (but is not attached to field.id) you can fix it with:
ALTER SEQUENCE field_seq OWNED BY field.id;
ALTER TABLE field
ALTER COLUMN id SET DEFAULT (nextval('field_seq'::regclass));
Make sure the sequence isn't in use for something else, though.
It would be much simpler to create your table like this to begin with:
CREATE TABLE field
(
id bigserial PRIMARY KEY,
...
);
Details on serial or bigserial in the manual.
Not sure how the the Play framework implements this.
This works.
insert into field (id, name) values (nextval('field_seq'), "Me");

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '' for column 'Date_Of_Birth' at row 1

I'm trying to update the personal detail of a user through a java panel.Panel has fields like user_id(autogenerated),name,date of birth.
problem is when i enter nothing to the date of birth field in java panel and then save it. It gives me the above mentioned error.
i tried to verify it by inserting null to the date of birth(Date datatype) field directly using the mysql database.There it gives no error.
Why is it not taking null string when i insert through java panel but is taking when insert directly using mysql.
CREATE TABLE `userpersonaldetail` (
`User_Id` int(10) unsigned NOT NULL auto_increment,
`Name` varchar(45) default NULL,
`Date_Of_Birth` date default NULL,
`Address` varchar(300) default NULL,
`Phone` varchar(20) default NULL,
`Mobile` varchar(20) default NULL,
`Email` varchar(50) default NULL,
PRIMARY KEY (`User_Id`),
CONSTRAINT `FK_userpersonaldetail_1` FOREIGN KEY (`User_Id`) REFERENCES `usermaster` (`User_Id`)
)
And the portion of the code where exception occurs is:
try
{
con=(Connection) DBConnection.getConnection();
pstmt=(PreparedStatement) con.prepareStatement("Update userpersonaldetail set "+
"name=?,date_of_birth=?,address=?,phone=?,mobile=?,email=? where user_id=?");
pstmt.setInt(7,perBean.getUserId());
pstmt.setString(1,perBean.getName());
pstmt.setString(2,perBean.getDateOfBirth());
pstmt.setString(3,perBean.getAddress());
pstmt.setString(4,perBean.getPhone());
pstmt.setString(5,perBean.getMobile());
pstmt.setString(6,perBean.getEmail());
int i=pstmt.executeUpdate();
}
here perBean is the javaBean which retrieves values from the gui.In one of the test case i kept the date_of_birth text box null which is giving error while storing in DB.
My initial guess would be the field has been defined as 'NOT NULL' which means it will force you to enter a value...
If you were to do a mysql dump of the table (or view it in some tool) you'll probably find it defined such as:
`someDT` datetime NOT NULL
I replaced older version of my-sql-connector jar (to be found in lib folder of the server) with the latest. That solved my problem.
Ahh, i see now, you can't insert '' as a date. you will need to pass a date.
If an attribute does not have a value but you have it mentioned in the column list, forcing you to give something there, you need to use
statement.setNull(index, datatype)
to it. Setting to "" is not the same thing as setting to null.

Categories

Resources