Linq and retrieving primary key - linq

This code works, but i dont understand why. With DeferredLoadingEnabld = false, I would expect it not to return the primary key. Can someone explain what I am missing?
public void SaveOrder (Order order)
{
using (DataContext dc= new DataContext)
{
dc.DeferredLoadingEnabled = false;
...
order.Total= total;
dc.order.InsertOnSubmit(order);
dc.SubmitChanges();
}
}
IN ORDER SERVICE:
public void ServiceSaveOrder(Order order)
{
Order order= new Order();
SaveOrder(order);
Print(order.ID); //ID= unique primary key
}

DeferredLoadingEnabled property is simply used for populating other relationships across foreign keys and not for returning IDs back after inserts. Your keys will always be populated. With DeferredLoadingEnabled set to true, any parent or child relationships will not automatically populated.
More information is available at the MSDN article.

Related

How is possible the Map will find the right element, when the HasCode() of that element has changed?

From my previous question: Hibernate: Cannot fetch data back to Map<>, I was getting NullPointerException after I tried to fetch data back. I though the reason was the primary key (when added to Map as put(K,V), the primary key was null, but after JPA persist, it created the primary key and thus changed the HashMap()). I had this equals and hashCode:
User.java:
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(username, user.username) && Objects.equals(about, user.about) && Objects.equals(friendships, user.friendships) && Objects.equals(posts, user.posts);
}
#Override
public int hashCode() {
return Objects.hash(id, username, about, friendships, posts);
}
-> I used all fields in the calculation of hash. That made the NullPointerException BUT not because of id (primary key), but because of collections involved in the hash (friends and posts). So I changed both functions to use only database equality:
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (id == null) return false;
if (!(o instanceof User)) return false;
User user = (User) o;
return this.id.equals(user.getId());
}
#Override
public int hashCode() {
return id == null ? System.identityHashCode(this) :
id.hashCode();
So now only the id field is involved in the hash. Now, it didn't give me NullPointerException for fetched data. I used this code to test it:
(from User.java):
public void addFriend(User friend){
Friendship friendship = new Friendship();
friendship.setOwner(this);
friendship.setFriend(friend);
this.friendships.put(friend, friendship);
}
DemoApplication.java:
#Bean
public CommandLineRunner dataLoader(UserRepository userRepo, FriendshipRepository friendshipRepo){
return new CommandLineRunner() {
#Override
public void run(String... args) throws Exception {
User f1 = new User("friend1");
User f2 = new User("friend2");
User u1 = new User("user1");
System.out.println(f1);
System.out.println(f1.hashCode());
u1.addFriend(f1);
u1.addFriend(f2);
userRepo.save(u1);
User fetchedUser = userRepo.findByUsername("user1");
System.out.println(fetchedUser.getFriendships().get(f1).getFriend());
System.out.println(fetchedUser.getFriendships().get(f1).getFriend().hashCode());
}
};
}
You can see I am
puting the f1 User into friendship of user1 (owner of the friendship). The time when the f1.getId() == null
saving the user1. The time when the f1 id gets assign its primary key value by Hibernate (because the friendship relation is Cascade.All so including the persisting)
Fetching the f1 User back by geting it from the Map, which does the look-up with the hashCode, which is now broken, because the f1.getId() != null.
But even then, I got the right element. The output:
User{id=null, username='friend1', about='null', friendships={}, posts=[]}
-935581894
...
User{id=3, username='friend1', about='null', friendships={}, posts=[]}
3
As you can see: the id is null, then 3 and the hashCode is -935581894, then 3... So how is possible I was able to get the right element?
Not all Map implementation use the hashCode (for example a TreeMap implementation do not use it, and rather uses a Comparator to sort entries into a tree).
So i would first check that hibernate is not replacing the field :
private Map<User, Friendship> friendships = new HashMap<>();
with its own implementation of Map.
Then, even if hibernate keeps the HashMap, and the hashcode of the object changed, you might be lucky and both old and new hashcodes gives the same bucket of the hashmap.
As the object is the same (the hibernate session garantees that), the equals used to find the object in the bucket will work. (if the bucket has more than 8 elements, instead of the bucket being a linked list, it will be a b-tree ordered on hashcode, in that case it won't find your entry, but the map seems to have only 2-3 elements so it can't be the case).
Now I understood your question.
Looking at the Map documentation we read the following:
Note: great care must be exercised if mutable objects are used as map
keys. The behavior of a map is not specified if the value of an object
is changed in a manner that affects equals comparisons while the
object is a key in the map.
It looks like there is no definitive answer for this and as #Thierry already said it seems that you just got lucky. The key takeaway is "do not use mutable objects as Map keys".

Spring Boot JPA : identifier of an instance of bingo.model.Group was altered from 1702 to null

I have a Short Question:
Last Save is working(Last Save will be Update).
But First Save is not working.(First Save will be Insert)
I can't insert this way, how is it possible?
#GetMapping(value = "/delete/{id}")
public String delete(#PathVariable BigInteger id, Model model) {
try {
Group group = groupService.findById(id);
group.setId(null);
group.isLog(true);
// This Save will be Insert Data
groupService.save(group);
group = groupService.findById(id);
group.isLog(true);
//This Save will be Update Data
groupService.save(group);
return "redirect:/accountsGroup/";
} catch (Exception ex) {
return "masters/accountsInfo/groups/index";
}
}
You can't just set the ID null.
The entity is in a managed state and will not be new just because you set the ID to null.
The proper way would be to clone the entity state in a new instance.
You could also try to detach the entity (EntityManager.detach) and then set the ID to null. Maybe it will insert a new row. But as I said this is not the way you should do that.
Read more about entity states here: https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/

MVC - Adding data into linker tables

I have a registration form that allows a school to register. In addition to the obvious login and general details the school can pick from a list of facilities and accreditations that they have.
My data is displayed lovely and binded correctly.
Problem Entering the data into the linker tables does not work it throws an error in both the different ways that I have tried:
Method1:
MembershipUser membershipUser = null;
if (schoolRegisterModel != null)
{
if (null != DB)
{
school SchoolUser = new school();
SchoolUser.username = schoolRegisterModel.UserName;
SchoolUser.email = schoolRegisterModel.Email;
string sPassowrdSalt = Security.Instance().CreateSalt();
SchoolUser.password = Security.Instance().CreatePasswordHash(schoolRegisterModel.Password, sPassowrdSalt);
SchoolUser.password_salt = sPassowrdSalt;
..More data etc..
foreach (var item in schoolRegisterModel.Facilities)
{
if (item.#checked)
{
school_facility sf = new school_facility();
sf.facility_id = item.facility_id;
SchoolUser.school_facility.Add(sf);
}
}
foreach (var item in schoolRegisterModel.Accreditations)
{
if (item.#checked)
{
school_accreditation sa = new school_accreditation();
sa.accreditation_id = item.accreditation_id;
SchoolUser.school_accreditation.Add(sa);
}
}
DB.schools.Add(SchoolUser);
DB.SaveChanges();
Error: {"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_school_facility_facility\". The conflict occurred in database \"MYDB\", table \"dbo.facility\", column 'facility_id'.\r\nThe statement has been terminated."}
Also - Do I need to manually retrieve the soon to be school ID that will be generated based on this insert. This method avoids entering data directly into the linker tables using only the primary table (school).
Method2:
Same code again apart from trying to update the primary tables (school) accreditation and facilities collection directly, I manually update the linker tables seperately using the latest primary key generated by the previous query, code for this is as follows:
MembershipUser membershipUser = null;
if (schoolRegisterModel != null)
{
if (null != DB)
{
school SchoolUser = new school();
SchoolUser.username = schoolRegisterModel.UserName;
SchoolUser.email = schoolRegisterModel.Email;
string sPassowrdSalt = Security.Instance().CreateSalt();
SchoolUser.password = Security.Instance().CreatePasswordHash(schoolRegisterModel.Password, sPassowrdSalt);
SchoolUser.password_salt = sPassowrdSalt;
..More data etc..
// Linker data for facilities and accreditations.
// Facilities
foreach (var item in schoolRegisterModel.Facilities)
{
if (item.#checked)
{
school_facility sf = new school_facility();
sf.facility_id = item.facility_id;
sf.school_id = SchoolUser.school_id;
DB.school_facility.Add(sf);
}
}
// Accreditations
foreach (var item in schoolRegisterModel.Accreditations)
{
if (item.#checked)
{
school_accreditation sa = new school_accreditation();
sa.accreditation_id = item.accreditation_id;
sa.school_id = SchoolUser.school_id;
DB.school_accreditation.Add(sa);
}
}
m_DB.SaveChanges();
Error: {"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_school_facility_facility\". The conflict occurred in database \"MYDB\", table \"dbo.facility\", column 'facility_id'.\r\nThe statement has been terminated."}
If you guys have any idea where I am going wrong then please do let me know. There seem to be examples of updating linker table date (which I will need at some point anyway) but can't find an example of my problem...
Thanks in advance.
Looks like I have found the answer:
MVC: The INSERT statement conflicted with the FOREIGN KEY constraint
My data being pulled through was basically not containing the correct foreign key value (0 - which didn't exist) and quite rightly my DB was throwing the error. Sorry for wasting time to whoever read and thanks for your time. I hope this can help somebody else.
Joe

How to retrive a generated primary key when a new row is inserted in the oracle database using Spring JDBC?

Below is the code I am using to save a record in the database and then get the generated primary key.
public void save(User user) {
// TODO Auto-generated method stub
Object[] args = { user.getFirstname(), user.getLastname(),
user.getEmail() };
int[] types = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
SqlUpdate su = new SqlUpdate();
su.setJdbcTemplate(getJdbcTemplate());
su.setSql(QUERY_SAVE);
setSqlTypes(su, types);
su.setReturnGeneratedKeys(true);
su.compile();
KeyHolder keyHolder = new GeneratedKeyHolder();
su.update(args, keyHolder);
int id = keyHolder.getKey().intValue();
if (su.isReturnGeneratedKeys()) {
user.setId(id);
} else {
throw new RuntimeException("No key generated for insert statement");
}
}
But its not working, It gives me following error.
The generated key is not of a supported numeric type. Unable to cast [oracle.sql.ROWID] to [java.lang.Number]
The row is being inserted in the database properly. As well I could get the generataed primary key when using MS SQL database but the same code is not working with the ORACLE 11G.
Please help.
As in the comment, oracle rowid's are alpha numerical so can't be cast to an int.
Besides that, you should not use the generated rowid anywhere in your code. This is not the primary key that you defined on the table.
MS SQL has the option to declare a column as a primary key which auto-increments. This is a functionality that does not work in oracle.
What I always do (regardless if the db supports auto-increment) is the following:
select sequenceName.nextval from dual
The value returned by the previous statement is used as the primary key for the insert statement.
insert into something (pk, ...) values (:pk,:.....)
That way we always have the pk after the insert.

linqToSql related table not delay loading properly. Not populating at all

I have a couple of tables with similar relationship structure to the standard Order, OrderLine tables.
When creating a data context, it gives the Order class an OrderLines property that should be populated with OrderLine objects for that particular Order object.
Sure, by default it will delay load the stuff in the OrderLine property but that should be fairly transparent right?
Ok, here is the problem I have: I'm getting an empty list when I go MyOrder.OrderLines but when I go myDataContext.OrderLines.Where(line => line.OrderId == 1) I get the right list.
public void B()
{
var dbContext = new Adis.CA.Repository.Database.CaDataContext(
"<connectionString>");
dbContext.Connection.Open();
dbContext.Transaction = dbContext.Connection.BeginTransaction();
try
{
//!!!Edit: Imortant to note that the order with orderID=1 already exists
//!!!in the database
//just add some new order lines to make sure there are some
var NewOrderLines = new List<OrderLines>()
{
new OrderLine() { OrderID=1, LineID=300 },
new OrderLine() { OrderID=1, LineID=301 },
new OrderLine() { OrderID=1, LineID=302 },
new OrderLine() { OrderID=1, LineID=303 }
};
dbContext.OrderLines.InsertAllOnSubmit(NewOrderLines);
dbContext.SubmitChanges();
//this will give me the 4 rows I just inserted
var orderLinesDirect = dbContext.OrderLines
.Where(orderLine => orderLine.OrderID == 1);
var order = dbContext.Orders.Where(order => order.OrderID == 1);
//this will be an empty list
var orderLinesThroughOrder = order.OrderLines;
}
catch (System.Data.SqlClient.SqlException e)
{
dbContext.Transaction.Rollback();
throw;
}
finally
{
dbContext.Transaction.Rollback();
dbContext.Dispose();
dbContext = null;
}
}
So as far as I can see, I'm not doing anything particularly strange but I would think that orderLinesDirect and orderLinesThroughOrder would give me the same result set.
Can anyone tell me why it doesn't?
You're just adding OrderLines; not any actual Orders. So the Where on dbContext.Orders returns an empty list.
How you can still find the property OrderLines on order I don't understand, so I may be goofing up here.
[Edit]
Could you update the example to show actual types, especially of the order variable? Imo, it shoud be an IQueryable<Order>, but it's strange that you can .OrderLines into that. Try adding a First() or FirstOrDefault() after the Where.

Resources