Enity Framework Issue- - entity-framework

i have table name M_Lovs with columns TITLE,TYPE_ID,IS_ACTIVE,AMD_BY,AMD_ON and ID. ID is primary key and its autoincremented. When i try to save my table using entity framework it throws 'System.Data.Entity.Infrastructure.DbUpdateException'.. when i checked the inner exception i found '{"An error occurred while updating the entries. See the inner exception for details."}' exception.
My code is as follows
M_LOVS lov = new M_LOVS();
lov.TITLE = masterData.Title;
lov.TYPE_ID = masterData.Type;
lov.IS_ACTIVE = masterData.IsActive ? 1 : 0;
lov.AMD_BY = addedBy;
lov.AMD_ON = DateTime.Now;
dbContext.M_LOVS.Add(lov);
dbContext.SaveChanges();

Related

primary key ID gives me repeated " 0 " value with android app

I try to make contactsApp with android , when I debug it the primary key repeat its value which is zero
AND HERE IS THE SQLiteOpenHelper class :
// get all Contacts
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
// HERE is where the error come...
try{
if (cursor.getString(0) != null)
contact.setId(Integer.parseInt(cursor.getString(0)));
}catch (Exception e){e.printStackTrace();}
contact.setName(cursor.getString(1) );
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
at first the error was NonNullException at this line
contact.setId(Integer.parseInt(cursor.getString(0)));
so I surround it with try catch then the app debug correctly but still gives wrong value for the INTEGER PRIMARY KEY id
the final result should be like
ID: 1, Name 1 , 111111111
ID: 2, Name 2 , 22222222
ID: 3, Name 3 , 33333333
ID: 4, Name 4 , 444444444
But I get this result..
ID: 0, Name 1 , 111111111
ID: 0, Name 2 , 22222222
ID: 0, Name 3 , 33333333
ID: 0, Name 4 , 444444444
after some searches I did not find any solution for that!
So what should I do to fix it ??
Thanks in advance!
EDIT
The stack-trace :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.muhamad_galal.databaseintro, PID: 3947
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.muhamad_galal.databaseintro/com.example.muhamad_galal.databaseintro.MainActivity}: java.lang.NumberFormatException: Invalid int: "null"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NumberFormatException: Invalid int: "null"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at Data.DataBaseHandler$override.getAllContact(DataBaseHandler.java:141)
at Data.DataBaseHandler$override.access$dispatch(DataBaseHandler.java)
at Data.DataBaseHandler.getAllContact(DataBaseHandler.java)
at com.example.muhamad_galal.databaseintro.MainActivity$override.onCreate(MainActivity.java:29)
at com.example.muhamad_galal.databaseintro.MainActivity$override.access$dispatch(MainActivity.java)
at com.example.muhamad_galal.databaseintro.MainActivity.onCreate(MainActivity.java)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077) 
at android.app.ActivityThread.-wrap15(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
What the message is saying is that you've passed a null to the Integer's parseInt method. as per :-
Caused by: java.lang.NumberFormatException: Invalid int: "null"
Thus it appears that the first column of the table has nulls.
At a guess you have not defined the column to be an alias of rowid and thus the column hasn't been given a unique integer value.
To be an alias of rowid it must be defined as INTEGER PRIMARY KEY or INTEGER PRIMARY KEY AUTOINCREMENT (the latter is not recommended).
If you changed :-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
// HERE is where the error come...
try{
if (cursor.getString(0) != null)
contact.setId(Integer.parseInt(cursor.getString(0)));
}catch (Exception e){e.printStackTrace();}
contact.setName(cursor.getString(1) );
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
to (see the comments at the end of lines that start with //<<<<) :-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT rowid,* FROM " + Util.TABLE_NAME; //<<<< CHANGED
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0)); //<<<< CHANGED to use getInt
contact.setName(cursor.getString(2)); //<<<< CHANGED to skip first column
contact.setPhoneNumber(cursor.getString(3)); //<<<< CHANGED to skip first column
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
Then I suspect that you would get the expected results.
This gets the normally hidden actual rowid column as well as all the other columns; so there is an extra column at the start.
Note this assumes that you haven't defined the table using WITHOUT ROWID
Really you should consider the id/rowid as a long but int will work as long as there aren't too many rows.
However, this should only be a temporary fix.
The full/permanent fix should be
Code the first column so that it is defined as an alias of rowid e.g. using CREATE TABLE you_table_name (ID INTEGER PRIMARY KEY, the_other_columns...... (this assumes that the column name is ID).
Delete the database by either uninstalling the App or by deleting the App's data.
This assumes that you do not require the current data.
Change the contact class so that the Id member is long not int.
Change the getters and setters in the contact class (setId and I assume getId) so that the methods use long rather than int
Change any other uses of the Id member of the contact class to use long.
Change the getAllContact method to be
:-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
delete the App's Data or uninstall the App.
rerun the App

Eclipselink ScrollableCursor fails on second next() call

I am trying to use ScrollableCursor for loading all users of the system to memory.
I have a code like this:
Query findUsersQuery
= entityManager.createNamedQuery(UserEntity.QUERY_ALL_USERS, UserEntity.class);
findUsersQuery.setHint(QueryHints.SCROLLABLE_CURSOR, Boolean.TRUE);
findUsersQuery.setHint(QueryHints.CURSOR_PAGE_SIZE, bulkSize);
findUsersQuery.setMaxResults(maxInitialCacheSize);
ScrollableCursor scrollableCursor = (ScrollableCursor) findUsersQuery.getSingleResult();
int leftSize = scrollableCursor.size();
while (scrollableCursor.hasNext()) {
int nextSize = leftSize > bulkSize ? bulkSize : leftSize;
List subscriberPrefs = scrollableCursor.next(nextSize);
leftSize -= nextSize;
//... Result list processing
}
The query is: SELECT s FROM UserEntity u order by u.userId
Size of result table is 100, when scrollableCursor.next(nextSize); called, i get following exception:
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLRecoverableException: Closed Resultset
Error Code: 17010
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.cursorRetrieveNextRow(DatabaseAccessor.java:447)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.retrieveNextObject(ScrollableCursor.java:563)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.loadNext(ScrollableCursor.java:411)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.next(ScrollableCursor.java:437)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.next(ScrollableCursor.java:459)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
While calling next(10) the first row loaded normally and the exceptions occurs on second row. I don't have an idea why. Can anybody say how i can avoid this error?

Salesforce Lead Trigger CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

I want to clone the Profile__c record. The lead has a profile__c associated with it. When conversion happens, the Profile_c on the lead is copied to the account created. What I need to do is a deep clone of the Profile__c on the new account created after the conversion. I am able to copy the profile_c over but cloning throws this error:
Error: System.DmlException: Update failed. First exception on row 0 with id 00QJ0000007dDmHMAU; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, profile: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: [] Trigger.profile:, column 1: [] (System Code)
trigger profile on Lead (after update) {
Map<Id, Lead> cl = new Map<Id,Lead>();
Lead parent;
List<Contact> clist = new List<Contact>();
Set<Id> convertedids = new Set<Id>();
//list of converted leads
for (Lead t:Trigger.new){
Lead ol = Trigger.oldMap.get(t.ID);
if(t.IsConverted == true && ol.isConverted == false)
{
cl.put(t.Id, t);
convertedids.add(t.ConvertedContactId);
}
}
Set<Id> leadIds = cl.keySet();
List<Profile__c> mp = [select Id, lock__c, RecordTypeId, reason__c, End_Date__c,startus__c , Opportunity__c, Account__c, Lead__c from Profile__c where Lead__c in :leadIds];
List<ID>AccountIDs = new List<ID>();
List<Profile__c>clonedList = new list<Profile__c>();
for (Profile__c mpi:mp){
parent = cl.get(mpi.Lead__c );
mpi.opportunity__c = parent.ConvertedOpportunityId;
mpi.account__c = parent.ConvertedAccountId;
AccountIDs.add(parent.ConvertedAccountId);
Profile__c profile = mpi.clone(false,true,false,false);
clonedList.add(profile);
mpi.lock__c= true;
mpi.reason__c= 'Converted';
}
update mp;
insert clonelist
}
You are doing insert operation(insert clonelist) in which you are accessing Converted lead Id value in a field. You can't use converted LeadId field in DML operations.
Below is the Sample code that will work-
trigger ConvertedLead_Trigger on Lead (after update) {
Map<Id, Lead> cl = new Map<Id,Lead>();
Lead parent;
List<Contact> clist = new List<Contact>();
Set<Id> convertedids = new Set<Id>();
//list of converted leads
for (Lead t:Trigger.new){
Lead ol = Trigger.oldMap.get(t.ID);
if(t.IsConverted == true && ol.isConverted == false)
{
cl.put(t.Id, t);
convertedids.add(t.ConvertedContactId);
}
}
Set<Id> leadIds = cl.keySet();
List<ConvertLeadTest__c> mp =[Select Id,Name,Lead__c, Account__c,Opportunity__c from ConvertLeadTest__c where Lead__c in :leadIds];
List<ConvertLeadTest__c> mp1=new List<ConvertLeadTest__c>();
List<ConvertLeadTest__c> mp2=new List<ConvertLeadTest__c>();
for(ConvertLeadTest__c cc:mp)
{
if(cl.containsKey(cc.Lead__c))
{
cc.Account__c=cl.get(cc.Lead__c).ConvertedAccountId;
cc.Opportunity__c=cl.get(cc.Lead__c).ConvertedOpportunityId;
mp1.add(cc);
mp2.add(new ConvertLeadTest__c(Account__c=cl.get(cc.Lead__c).ConvertedAccountId,Opportunity__c=cl.get(cc.Lead__c).ConvertedOpportunityId));
}
}
update mp;
insert mp2;
}
But if you write
ConvertLeadTest__c(Lead__c=cc.Lead__c,Account__c=cl.get(cc.Lead__c).ConvertedAccountId,Opportunity__c=cl.get(cc.Lead__c).ConvertedOpportunityId));
then it will throw error.
Hope this will help you.
Thanks :)
We are not able to perform any operation on the Lead once the lead is converted.
Anything you do to try o update the converted lead will give you error.
What eventually did it for me was after the conversion, I grabbed the convertedAccountIds. Since I was already copying Profile__c to the account after conversion, I just cloned the profile there and had to set the lead on that profile to null since it can't be updated

Inserting composite row using fluent cassandra api

I created a composite primary key column family in cassandra
CREATE TABLE rMessage ( Key varchar,msg_id varchar, msg blob, PRIMARY KEY(key,msg_id) );
I am trying to create a record via Fluent cassandra api.
string key = "cat1";
string id = "2";
CompositeType compositeKey = new CompositeType<FluentCassandra.Types.AsciiType, FluentCassandra.Types.AsciiType>(key,id);
FluentColumnFamily record = ColumnFamily.CreateRecord(compositeKey.ToString());
dynamic r = record.AsDynamic();
r.msg = blob;
record.Columns[0].ColumnTimeUntilDeleted = diff;
Context.Attach(record);
Context.SaveChanges();
The above code return error "Not enough bytes to read value of component 0". I couldn't figure out why.
I tried the below approach but still getting the same error "Not enough bytes to read value of component 0".
var blob = CassandraBinaryFormatter.Serialzie(value);
var compositeKey = new CompositeType<FluentCassandra.Types.UTF8Type, FluentCassandra.Types.UTF8Type>(key, value.ID.ToString());
FluentColumnFamily record = ColumnFamily.CreateRecord(key);
record[compositeKey.ToString()] = blob;
Context.Attach(record);
Context.SaveChanges();
Thanks for help.

get primary key of last inserted record with JPA

I've been using JPA to insert entities into a database but I've run up against a problem where I need to do an insert and get the primary key of the record last inserted.
Using PostgreSQL I would use an INSERT RETURNING statement which would return the record id, but with an entity manager doing all this, the only way I know is to use SELECT CURRVAL.
So the problem becomes, I have several data sources sending data into a message driven bean (usually 10-100 messages at once from each source) via OpenMQ and inside this MDB I persists this to PostgreSQL via the entity manager. It's at this point I think there will be a "race condition like" effect of having so many inserts that I won't necessarily get the last record id using SELECT CURRVAL.
My MDB persists 3 entity beans via an entity manager like below.
Any help on how to better do this much appreciated.
public void onMessage(Message msg) {
Integer agPK = 0;
Integer scanPK = 0;
Integer lookPK = 0;
Iterator iter = null;
List<Ag> agKeys = null;
List<Scan> scanKeys = null;
try {
iag = (IAgBean) (new InitialContext()).lookup(
"java:comp/env/ejb/AgBean");
TextMessage tmsg = (TextMessage) msg;
// insert this into table only if doesn't exists
Ag ag = new Ag(msg.getStringProperty("name"));
agKeys = (List) (iag.getPKs(ag));
iter = agKeys.iterator();
if (iter.hasNext()) {
agPK = ((Ag) iter.next()).getId();
}
else {
// no PK found so not in dbase, insert new
iag.addAg(ag);
agKeys = (List) (iag.getPKs(ag));
iter = agKeys.iterator();
if (iter.hasNext()) {
agPK = ((Ag) iter.next()).getId();
}
}
// insert this into table always
iscan = (IScanBean) (new InitialContext()).lookup(
"java:comp/env/ejb/ScanBean");
Scan scan = new Scan();
scan.setName(msg.getStringProperty("name"));
scan.setCode(msg.getIntProperty("code"));
iscan.addScan(scan);
scanKeys = (List) iscan.getPKs(scan);
iter = scanKeys.iterator();
if (iter.hasNext()) {
scanPK = ((Scan) iter.next()).getId();
}
// insert into this table the two primary keys above
ilook = (ILookBean) (new InitialContext()).lookup(
"java:comp/env/ejb/LookBean");
Look look = new Look();
if (agPK.intValue() != 0 && scanPK.intValue() != 0) {
look.setAgId(agPK);
look.setScanId(scanPK);
ilook.addLook(look);
}
// ...
The JPA spec requires that after persist, the entity be populated with a valid ID if an ID generation strategy is being used. You don't have to do anything.