ERROR: null value in column "album_id" of relation "songs" violates not-null constraint - spring

The entity classes are as given below
I am not sure if this is problem with how Hibernate or Spring Data understands my input. In my project on backend I am using Java + Spring Data + Hibernate + PostgreSQL.
I am able to get and delete data from the database but not add to it.
//AlbumEntity
``
#Entity
#Table(name = "albums")
public class AlbumEntity extends ApplicationPersistenceEntity implements Album {
#Id
#Column(name = "album_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long albumId;
#Column(name = "NAME")
private String albumName;
#Column(name = "Genre")
private String genre;
#ManyToOne(cascade = CascadeType.PERSIST, optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "singer_id", nullable = false)
// #NotFound(action = NotFoundAction.IGNORE)
private SingerEntity singer;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "album")
private List<SongEntity> songs;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public AlbumEntity() {
}
/**
* The constructor.
*
* #param albumId
* #param albumName
* #param genre
* #param singer
* #param songs
*/
public AlbumEntity(long albumId, String albumName, String genre, SingerEntity singer, List<SongEntity> songs) {
super();
this.albumId = albumId;
this.albumName = albumName;
this.genre = genre;
this.singer = singer;
this.songs = songs;
}
/**
* #return albumId
*/
#Override
public long getAlbumId() {
return this.albumId;
}
/**
* #param albumId new value of {#link #getalbumId}.
*/
#Override
public void setAlbumId(long albumId) {
this.albumId = albumId;
}
/**
* #return albumName
*/
#Override
public String getAlbumName() {
return this.albumName;
}
/**
* #param albumName new value of {#link #getalbumName}.
*/
#Override
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
/**
* #return genre
*/
#Override
public String getGenre() {
return this.genre;
}
/**
* #param genre new value of {#link #getgenre}.
*/
#Override
public void setGenre(String genre) {
this.genre = genre;
}
/**
* #return singer
*/
public SingerEntity getSinger() {
return this.singer;
}
/**
* #param singer new value of {#link #getsinger}.
*/
public void setSinger(SingerEntity singer) {
this.singer = singer;
}
/**
* #return songs
*/
public List<SongEntity> getSongs() {
return this.songs;
}
/**
* #param songs new value of {#link #getsongs}.
*/
public void setSongs(List<SongEntity> songs) {
this.songs = songs;
}
#Override
#Transient
public Long getSingerId() {
if (this.singer == null) {
return null;
}
return this.singer.getId();
}
#Override
public void setSingerId(Long singerId) {
if (singerId == null) {
this.singer = null;
} else {
SingerEntity singerEntity = new SingerEntity();
singerEntity.setId(singerId);
this.singer = singerEntity;
}
}
}
//Song Entity
#Entity
#Table(name = "songs")
public class SongEntity extends ApplicationPersistenceEntity implements Song {
#Id
#Column(name = "song_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long songId;
#Column(name = "Title")
private String title;
#Column(name = "Content")
private String content;
#ManyToOne(cascade = CascadeType.PERSIST, optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "singer_id", nullable = false)
private SingerEntity singer;
#ManyToOne(cascade = CascadeType.PERSIST, optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "album_id")
private AlbumEntity album;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public SongEntity() {
}
/**
* The constructor.
*
* #param songId
* #param title
* #param content
* #param singer
* #param album
*/
public SongEntity(long songId, String title, String content, SingerEntity singer, AlbumEntity album) {
super();
this.songId = songId;
this.title = title;
this.content = content;
this.singer = singer;
this.album = album;
}
/**
* #return songId
*/
#Override
public long getSongId() {
return this.songId;
}
/**
* #param songId new value of {#link #getsongId}.
*/
#Override
public void setSongId(long songId) {
this.songId = songId;
}
/**
* #return title
*/
#Override
public String getTitle() {
return this.title;
}
/**
* #param title new value of {#link #gettitle}.
*/
#Override
public void setTitle(String title) {
this.title = title;
}
/**
* #return content
*/
#Override
public String getContent() {
return this.content;
}
/**
* #param content new value of {#link #getcontent}.
*/
#Override
public void setContent(String content) {
this.content = content;
}
/**
* #return singer
*/
public SingerEntity getSinger() {
return this.singer;
}
/**
* #param singer new value of {#link #getsinger}.
*/
public void setSinger(SingerEntity singer) {
this.singer = singer;
}
/**
* #return album
*/
public AlbumEntity getAlbum() {
return this.album;
}
/**
* #param album new value of {#link #getalbum}.
*/
public void setAlbum(AlbumEntity album) {
this.album = album;
}
#Override
#Transient
public Long getSingerId() {
if (this.singer == null) {
return null;
}
return this.singer.getId();
}
#Override
public void setSingerId(Long singerId) {
if (singerId == null) {
this.singer = null;
} else {
SingerEntity singerEntity = new SingerEntity();
singerEntity.setId(singerId);
this.singer = singerEntity;
}
}
#Override
#Transient
public Long getAlbumId() {
if (this.album == null) {
return null;
}
return this.album.getId();
}
#Override
public void setAlbumId(Long albumId) {
if (albumId == null) {
this.album = null;
} else {
AlbumEntity albumEntity = new AlbumEntity();
albumEntity.setId(albumId);
this.album = albumEntity;
}
}
}
singer entity
#Entity
#Table(name = "singers")
public class SingerEntity extends ApplicationPersistenceEntity implements Singer {
#Id
#Column(name = "singer_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long singerId;
#Column(name = "First_NAME")
private String firstname;
#Column(name = "Last_NAME")
private String lastname;
#Column(name = "Gender")
private String gender;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "singer")
private List<SongEntity> songs;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "singer")
private List<AlbumEntity> albums;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public SingerEntity() {
}
/**
* The constructor.
*
* #param singerId
* #param firstname
* #param lastname
* #param gender
* #param songs
* #param albums
*/
public SingerEntity(long singerId, String firstname, String lastname, String gender, List<SongEntity> songs,
List<AlbumEntity> albums) {
super();
this.singerId = singerId;
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
this.songs = songs;
this.albums = albums;
}
/**
* #return singerId
*/
#Override
public long getSingerId() {
return this.singerId;
}
/**
* #param singerId new value of {#link #getsingerId}.
*/
#Override
public void setSingerId(long singerId) {
this.singerId = singerId;
}
/**
* #return firstname
*/
#Override
public String getFirstname() {
return this.firstname;
}
/**
* #param firstname new value of {#link #getfirstname}.
*/
#Override
public void setFirstname(String firstname) {
this.firstname = firstname;
}
/**
* #return lastname
*/
#Override
public String getLastname() {
return this.lastname;
}
/**
* #param lastname new value of {#link #getlastname}.
*/
#Override
public void setLastname(String lastname) {
this.lastname = lastname;
}
/**
* #return gender
*/
#Override
public String getGender() {
return this.gender;
}
/**
* #param gender new value of {#link #getgender}.
*/
#Override
public void setGender(String gender) {
this.gender = gender;
}
/**
* #return songs
*/
public List<SongEntity> getSongs() {
return this.songs;
}
/**
* #param songs new value of {#link #getsongs}.
*/
public void setSongs(List<SongEntity> songs) {
this.songs = songs;
}
/**
* #return albums
*/
public List<AlbumEntity> getAlbums() {
return this.albums;
}
/**
* #param albums new value of {#link #getalbums}.
*/
public void setAlbums(List<AlbumEntity> albums) {
this.albums = albums;
}
}
While checking Post endpoint
"modificationCounter": 2,
"id": 302,
"songId": 302,
"title": "As it was",
"content": "songs",
"singer_id": 201,
"album_id": 101
I am giving this data...still there is this error
org.postgresql.util.PSQLException: ERROR: null value in column "album_id" of relation "songs" violates not-null constraint
Detail: Failing row contains (302, 2, 302, As it was, songs, null, null).

This one keeps on coming... I guess you are using your entities as DTOs. DON'T
The problem is that you send an ID for albumID and singerID which are objects in Java.
For this to work, create a DTO that maps your fields and lookup the IDs in your database then create your Song Entity with those. Also, you need to map back the song in your album and singer for JPA to work correctly.

Related

Spring Boot test #After not deleting rows before next test

I have the following #Before and #After in my Spring Boot integration tests:
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.addFilter(springSecurityFilterChain).build();
user = userRepository.save(
new User("Joe", "Bloggs", "joe#example.com", "joe", passwordEncoder.encode("secret")));
currency = currencyRepository.save(
new Currency("GBP", "£%01.2f"));
fund = fundRepository.save(
new Fund("Nationwide", (double) 100, currency));
}
#After
public void teardown() {
userRepository.delete(user);
currencyRepository.delete(currency);
fundRepository.delete(fund);
}
However, it doesn't seem that currencies are being deleted after each test and my tests are failing in error:
...
[ERROR] testGetFunds_whenNoToken_thenUnauthorized(biz.martyn.budget.FundsControllerTest) Time elapsed: 3.268 s <<< ERROR!
org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find biz.martyn.budget.currency.Currency with id 437; nested exception is javax.persistence.EntityNotFoundException: Unable to find biz.martyn.budget.currency.Currency with id 437
Caused by: javax.persistence.EntityNotFoundException: Unable to find biz.martyn.budget.currency.Currency with id 437
...
After, if I query the test database, I see that rows haven't been deleted:
mysql> select * from currencies;
+----+---------------------+---------------------+---------------+------+---------------------+
| id | created_at | deleted_at | format | name | updated_at |
+----+---------------------+---------------------+---------------+------+---------------------+
...
| 437 | 2020-01-02 13:51:24 | 2020-01-02 13:51:23 | £%01.2f | GBP | 2020-01-02 13:51:24 |
...
+----+---------------------+---------------------+---------------+------+---------------------+
5 rows in set (0.00 sec)
There should only be one unique entry for name but I guess as delete is not happening it is pulling duplicates for "GBP". My repository for currencies:
Currency.java
#Entity(name = "currencies")
#SQLDelete(sql = "UPDATE currencies SET deleted_at = now() WHERE id = ?")
#Where(clause = "deleted_at is null")
public class Currency {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id;
#Column(unique = true, nullable = false)
private String name;
#Column(nullable = false)
private String format;
#Column(name = "created_at", updatable = false)
#CreationTimestamp
protected LocalDateTime createdAt;
#Column(name = "updated_at")
#UpdateTimestamp
protected LocalDateTime updatedAt;
#Column(name = "deleted_at")
protected LocalDateTime deletedAt;
protected Currency() {}
public Currency(String name, String format) {
this.name = name;
this.format = format;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getFormat() {
return format;
}
public void setFormat(final String format) {
this.format = format;
}
}
User.java
#Entity(name = "users")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8507204786382662588L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String surname;
#Column(nullable = false, unique = true)
private String email;
#Column(nullable = false, unique = true)
private String username;
#Column(nullable = false)
#JsonIgnore
private String password;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name="user_id")
#JsonIgnore
private List<Fund> funds;
protected User() {}
public User(String firstName, String surname, String email, String username, String password) {
this.firstName = firstName;
this.surname = surname;
this.email = email;
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// standard getters and setters
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Fund> getFunds() {
return funds;
}
public void addFund(Fund fund) {
funds.add(fund);
fund.setUser(this);
}
public void removeFund(Fund fund) {
funds.remove(fund);
fund.setUser(null);
}
// public Fund getFund(int id) {
// fundRepository.findByIdAndUserId(id)
// .orElseThrow(() -> new EntityNotFoundException("Fund ID not found: "+id));
// }
}
The delete method takes an object of Currency. Your Currency object has an ID which is auto-generated.
When you pass the same object that you passed to save to delete you did not set the ID that's the reason the delete operation never actually deletes the data you wanted to delete.
You can either use the object that is returned from save method or get a hold of the genearted-id and use deleteById method.
Here is an example for delete using the object.
#Before
public void setup() {
user = repository.save(user);
}
#After
public void tearDown() {
repository.delete(user);
}
Alternatively, you can use the same object to get the generated-id and use deleteById method.
If you take a look at SimpleJpaRepository which provides an implementation for JPA, you will find that if your ID is null then they are treated as a new entity and are never deleted.
/*
* (non-Javadoc)
* #see org.springframework.data.repository.CrudRepository#delete(java.lang.Object)
*/
#Override
#Transactional
#SuppressWarnings("unchecked")
public void delete(T entity) {
Assert.notNull(entity, "Entity must not be null!");
if (entityInformation.isNew(entity)) {
return;
}
// Other stuff
}

Stop hibernate from firing update query on #ManyToOne entities

I have two entities ProductCartItem and Product. A product in my scenario is more of a master record that is never gonna change. Below is the mapping.
#Entity
#DiscriminatorValue(value = "PRODUCT")
public class ProductCartItem extends CartItem {
#ManyToOne(optional = false)
#JoinColumn(name = "product_id", referencedColumnName = "id")
private Product product;
#OneToMany(cascade = CascadeType.REMOVE, mappedBy = "parentProductCartItem",orphanRemoval = true)
#JsonManagedReference
Set<AccessoryCartItem> associatedAccessories = new HashSet<>();
#Column(name="property")
#Type(type = "ProductItemPropertyUserType")
private ProductItemProperty productItemProperty;
#OneToOne
#JoinColumn(name="project_id",referencedColumnName = "id")
private Project project;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Set<AccessoryCartItem> getAssociatedAccessories() {
return associatedAccessories;
}
public void setAssociatedAccessories(Set<AccessoryCartItem> associatedAccessories) {
this.associatedAccessories = associatedAccessories;
}
public void addAccessory(AccessoryCartItem accessoryCartItem) {
this.getAssociatedAccessories().add(accessoryCartItem);
}
public void removeAccessory(AccessoryCartItem accessoryCartItem) {
this.getAssociatedAccessories().remove(accessoryCartItem);
}
public ProductItemProperty getProductItemProperty() {
return productItemProperty;
}
public void setProductItemProperty(ProductItemProperty productItemProperty) {
this.productItemProperty = productItemProperty;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
And here is the Product entity.
#Entity
public class Product extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "title")
private String title;
#Column(name = "subtitle")
private String subtitle;
#Column(name = "description")
private String description;
#Column(name = "type_name")
private String typeName;
#Column(name = "price")
private Float price;
#Column(name = "image_list")
#Type(type = "MyImageListUserType")
private MyImageList imageList;
#Column(name = "pricing_property")
#Type(type = "PricingProperty")
private Map<String,SizePriceDTO> pricingProperty;
#JoinColumn(name = "product_type")
#ManyToOne
private ProductType productType;
private String orientation;
private Short groupId;
#Column(name = "display_order")
private Short displayOrder;
#Column(name = "base_quantity")
private int baseQuantity;
#Transient
private List<AccessoryDTO> configuredAccessoryDTOList;
public Product(){
}
public int getBaseQuantity() {
return baseQuantity;
}
public void setBaseQuantity(int baseQuantity) {
this.baseQuantity = baseQuantity;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public MyImageList getImageList() {
return imageList;
}
public void setImageList(MyImageList imageList) {
this.imageList = imageList;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public String getOrientation() {
return orientation;
}
public void setOrientation(String orientation) {
this.orientation = orientation;
}
public Short getGroupId() {
return groupId;
}
public void setGroupId(Short groupId) {
this.groupId = groupId;
}
public Short getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Short displayOrder) {
this.displayOrder = displayOrder;
}
public List<AccessoryDTO> getConfiguredAccessoryDTOList() {
return configuredAccessoryDTOList;
}
public void setConfiguredAccessoryDTOList(List<AccessoryDTO> configuredAccessoryDTOList) {
this.configuredAccessoryDTOList = configuredAccessoryDTOList;
}
public Map<String, SizePriceDTO> getPricingProperty() {
return pricingProperty;
}
public void setPricingProperty(Map<String,SizePriceDTO> pricingProperty) {
this.pricingProperty = pricingProperty;
}
}
Now when I create a new ProductCartItem I associate an already existing Product with it. When I save the productcartitem hibernate for some reasons is firing an update query on the product table too. I have already tried setting the relationship as updatable= false but to no avail. Below is the code for the service.
private ShoppingCart addProductToCartHelper(ProductCartItemDTO productCartItemDTO) throws ShoppingException{
ShoppingCart shoppingCart;
ProductCartItem productCartItem;
Product product = productService.getProductById(productCartItemDTO.getProductDTO().getId().intValue());
if (null == product) {
throw new ShoppingException();
}
Customer currentCustomer = CanveraWebUtil.getCurrentCustomer();
GuestUser guestUser = guestUserService.loadGuestUserByUUID(CanveraWebUtil.getCurrentGuestUserIdentifier());
shoppingCart = fetchShoppingCartForCustomerOrGuestUser();
if (null == shoppingCart) {
if (null != currentCustomer) {
shoppingCart = new ShoppingCart(currentCustomer);
} else {
shoppingCart = new ShoppingCart(guestUser);
}
shoppingCart.setShoppingBagStatus(ShoppingBagStatus.DRAFT);
}
Long productCartItemDTOId = productCartItemDTO.getId();
// we will not update the associated accessories as in our case these never comes from our UI.
if (null == productCartItemDTOId) {
modifyNumberOfPages(productCartItemDTO,product);
productCartItem = new ProductCartItem();
productCartItem.setProductItemProperty(productCartItemDTO.getProductItemProperty());
productCartItem.setQuantity(productCartItemDTO.getQuantity());
productCartItem.setProduct(product);
productCartItem.setPrice(productCartItemDTO.getPrice());
productCartItem.setGiftWrap(shoppingCart.getIsGiftWrap());
//associating project
productCartItem.setProject(productCartItemDTO.getProject());
shoppingCart.addCartItem(productCartItem);
productCartItem.setShoppingCart(shoppingCart);
} else {
for (CartItem cartItem : shoppingCart.getCartItems()) {
if (null != cartItem.getId() && cartItem.getId().equals(productCartItemDTOId)) {
productCartItem = (ProductCartItem) cartItem;
productCartItem.setProductItemProperty(productCartItemDTO.getProductItemProperty());
productCartItem.setPrice(productCartItemDTO.getPrice());
productCartItem.setQuantity(productCartItemDTO.getQuantity());
}
}
}
shoppingCart = shoppingCartRepository.save(shoppingCart);
return shoppingCart;
}
Can anybody point me in the right direction ? At any point of time I do not alter any property of the product object.

Spring Security: authentication userdao is null

I have set up JSF with Spring Security.
I narrowed the problem down to the createCriteria method which returns nothing.
Any ideas?
Why does my userdao return null?
I have a MyUserDetailsService:
public class MyUserDetailsService implements UserDetailsService, Serializable {
/**
*
*/
private static final long serialVersionUID = 1864276199817921495L;
private UserDao userDao;
#Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
bla.bla.bla.model.User user = userDao.getUser(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getPermissions());
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(bla.bla.bla.model.User user,
List<GrantedAuthority> authorities) {
return new User(user.getUsername(),
user.getPassword(), user.getEnabled(),
true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<Permission> Permissions) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (Permission permission : Permissions) {
setAuths.add(new SimpleGrantedAuthority(permission.getPermission()));
}
List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
return Result;
}
/*
* Get the UserDao
*/
public UserDao getUserDao() {
return userDao;
}
/*
* Set the userDao
*/
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
I am able to get the final String username and pass it to userDao.getUser(username) but my method returns null for the user object so that when I access a method I get the following error:
[ERROR] org.springframework.security.web.authentication.UsernamePasswordAuthenticationFi lter:226 - An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException
This is what is called by getuser(username):
public GenericDaoImpl(final Class<T> type) {
super();
this.type = type;
}
#SuppressWarnings("unchecked")
public T getBySingleValue(String field, Object value){
Session session = sessionFactory.getCurrentSession();
try{
if(!session.getTransaction().isActive())
session.beginTransaction();
//Create a new Criteria instance, for the given entity class
//Executes a query against a particular persistent class
Criteria criteria = session.createCriteria(type);
criteria.add(Restrictions.eq(field, value));
T object = (T)criteria.uniqueResult();
return object;
} catch (Exception e){
System.out.println("ERROR");
e.printStackTrace();
return null;
} finally {
if(session.getTransaction().isActive())
session.getTransaction().commit();
}
}
Criteria criteria = session.createCriteria(type); returns null when it shouldn't. No hibernate sql statements are printed out.
My JPA mappings are here:
#Entity
#Table(name="users")
public class User {
private Integer id;
private String username;
private String firstname;
private String lastname;
private String password;
private Set<Permission> permissions = new HashSet<Permission>(0);
/**
* Default Constructor
*/
public User(){
}
public User(String username, String firstname,
String lastname,String password){
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
}
public User(String username, String firstname,
String lastname,String password,
Set<Permission> permissions) {
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.permissions = permissions;
}
/**Get the id
* #return the id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
/**Set the id
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**Get the username
* #return the username
*/
#Column(name="username", unique=true, nullable = false, length=25)
public String getUsername() {
return this.username;
}
/**Set the username
* #param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* #return the firstname
*/
#Column(name="firstname", nullable = false, length=20)
public String getFirstName() {
return this.firstname;
}
/**
* #param firstname the firstname to set
*/
public void setFirstName(String firstname) {
this.firstname = firstname;
}
/**
* #return the lastname
*/
#Column(name="lastname", nullable = false, length=20)
public String getLastName() {
return this.lastname;
}
/**
* #param lastname the lastname to set
*/
public void setLastName(String lastname) {
this.lastname = lastname;
}
/**
* #return the password
*/
#Column(name="password", nullable = false, length=60)
public String getPassword() {
return this.password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #return the userPermissions
*/
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="user_permission",
joinColumns = #JoinColumn(name="user_id", nullable=false),
inverseJoinColumns = #JoinColumn(name="permission_id",nullable=false))
public Set<Permission> getPermissions() {
return this.permissions;
}
/**
* #param userPermissions the userPermissions to set
*/
public void setPermissions(Set<Permission> userPermissions) {
this.permissions = userPermissions;
}
}
#Entity
#Table(name="permission")
public class Permission {
private Integer id;
private String permission;
private String description;
private Set<User> users = new HashSet<User>(0);
/**
* Default constructor
*/
public Permission(){
}
public Permission(String permission, String description,
Set<User> users) {
this.permission = permission;
this.description = description;
this.users = users;
}
/**
* #return the id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
/**
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* #return the permission
*/
#Column(name = "permission", unique = true, nullable = false, length = 50)
public String getPermission() {
return this.permission;
}
/**
* #param permission the permission to set
*/
public void setPermission(String permission) {
this.permission = permission;
}
/**
* #return the description
*/
#Column(name = "description", length = 150)
public String getDescription() {
return this.description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the users
*/
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "permissions")
public Set<User> getUsers() {
return this.users;
}
/**
* #param users the users to set
*/
public void setUsers(Set<User> users) {
this.users = users;
}
}
MY userDAO and MyUserServiceDetail is defined in xml file:
<bean id="userDao" class="bla.bla.bla.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myUserDetailsService"
class="bla.bla.bla.service.MyUserDetailsService">
<property name="userDao" ref="userDao" />
</bean>
I think my JPA mappings could be wrong...
Figured it out:
I added to hibernate session configuration:
<property name="annotatedClasses">
<list>
<value>bla.blah.bla.User</value>
<value>bla.blah.bla.model.UserOrganization</value>
<value>bla.blah.bla.model.Permission</value>
</list>
</property>

How to Manage Entity relatinships with hibernate in Google App engine

When I am having only 1 onetoMany relation code works fine. When I declare more that 1 #onetomany relation in an entity its breaks saying : org.hibernate.exception.SQLGrammarException: Unknown column 'userregist0_.jdoDetachedState' in 'field list' How this can be managed MY entity class is: package com.bullbeardevice.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The persistent class for the user_registration database table.
*
*/
#Entity
#Table(name = "user_registration")
#NamedQuery(name = "UserRegistration.findAll", query = "SELECT u FROM UserRegistration u")
#PersistenceCapable(identityType=IdentityType.APPLICATION, detachable="false")
public class UserRegistration implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_Registration_Id")
private String userRegistrationId;
#Column(name = "account_Status")
private int accountStatus;
#Column(name = "created_By")
private String createdBy;
#Column(name = "created_On")
#Temporal(TemporalType.TIMESTAMP)
private Date createdOn;
#Column(name = "email_Address")
private String emailAddress;
#Column(name = "expiry_Date")
#Temporal(TemporalType.TIMESTAMP)
private Date expiryDate;
#ManyToOne
#JoinColumn(name = "Group_Master_Id")
private GroupMaster groupMaster;
#Column(name = "modified_By")
private String modifiedBy;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modified_On")
private Date modifiedOn;
#Column(name = "user_password")
private String password;
#Column(name = "permissions")
private int permissions;
// bi-directional many-to-one association to Chat
#OneToMany(mappedBy = "userRegistration")
private List<Chat> chats;
// bi-directional many-to-one association to Coupon
#OneToMany(mappedBy = "userRegistration")
private List<Coupon> coupons;
// bi-directional many-to-one association to DeviceDetail
#OneToMany(mappedBy = "userRegistration")
private List<DeviceDetail> deviceDetails;
// bi-directional many-to-one association to Portfolio
#OneToMany(mappedBy = "userRegistration")
private List<Portfolio> portfolios;
// bi-directional many-to-one association to UserDetail
#OneToMany(mappedBy = "userRegistration")
private List<UserDetail> userDetails;
// bi-directional many-to-one association to UserLoginDetail
#OneToMany(mappedBy = "userRegistration")
private List<UserLoginDetail> userLoginDetails;
// bi-directional many-to-one association to UserRoleMaster
#ManyToOne
#JoinColumn(name = "User_Role_Master_Id")
private UserRoleMaster userRoleMaster;
// bi-directional many-to-one association to Watch
#OneToMany(mappedBy = "userRegistration")
private List<Watch> watches;
public UserRegistration() {
}
/**
* #return the userRegistrationId
*/
public String getUserRegistrationId() {
return userRegistrationId;
}
/**
* #param userRegistrationId
* the userRegistrationId to set
*/
public void setUserRegistrationId(String userRegistrationId) {
this.userRegistrationId = userRegistrationId;
}
/**
* #return the accountStatus
*/
public int getAccountStatus() {
return accountStatus;
}
/**
* #param accountStatus
* the accountStatus to set
*/
public void setAccountStatus(int accountStatus) {
this.accountStatus = accountStatus;
}
/**
* #return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* #param createdBy
* the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* #return the createdOn
*/
public Date getCreatedOn() {
return createdOn;
}
/**
* #param createdOn
* the createdOn to set
*/
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
/**
* #return the emailAddress
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* #param emailAddress
* the emailAddress to set
*/
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
/**
* #return the expiryDate
*/
public Date getExpiryDate() {
return expiryDate;
}
/**
* #param expiryDate
* the expiryDate to set
*/
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
/**
* #return the groupMaster
*/
public GroupMaster getGroupMaster() {
return groupMaster;
}
/**
* #param groupMaster
* the groupMaster to set
*/
public void setGroupMaster(GroupMaster groupMaster) {
this.groupMaster = groupMaster;
}
/**
* #return the modifiedBy
*/
public String getModifiedBy() {
return modifiedBy;
}
/**
* #param modifiedBy
* the modifiedBy to set
*/
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
/**
* #return the modifiedOn
*/
public Date getModifiedOn() {
return modifiedOn;
}
/**
* #param modifiedOn
* the modifiedOn to set
*/
public void setModifiedOn(Date modifiedOn) {
this.modifiedOn = modifiedOn;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #return the permissions
*/
public int getPermissions() {
return permissions;
}
/**
* #param permissions
* the permissions to set
*/
public void setPermissions(int permissions) {
this.permissions = permissions;
}
/**
* #return the chats
*/
public List<Chat> getChats() {
return chats;
}
/**
* #param chats
* the chats to set
*/
public void setChats(List<Chat> chats) {
this.chats = chats;
}
public Chat addChat(Chat chat) {
getChats().add(chat);
chat.setUserRegistration(this);
return chat;
}
public Chat removeChat(Chat chat) {
getChats().remove(chat);
chat.setUserRegistration(null);
return chat;
}
public List<Coupon> getCoupons() {
return this.coupons;
}
public void setCoupons(List<Coupon> coupons) {
this.coupons = coupons;
}
public Coupon addCoupon(Coupon coupon) {
getCoupons().add(coupon);
coupon.setUserRegistration(this);
return coupon;
}
public Coupon removeCoupon(Coupon coupon) {
getCoupons().remove(coupon);
coupon.setUserRegistration(null);
return coupon;
}
public List<DeviceDetail> getDeviceDetails() {
return this.deviceDetails;
}
public void setDeviceDetails(List<DeviceDetail> deviceDetails) {
this.deviceDetails = deviceDetails;
}
public DeviceDetail addDeviceDetail(DeviceDetail deviceDetail) {
getDeviceDetails().add(deviceDetail);
deviceDetail.setUserRegistration(this);
return deviceDetail;
}
public DeviceDetail removeDeviceDetail(DeviceDetail deviceDetail) {
getDeviceDetails().remove(deviceDetail);
deviceDetail.setUserRegistration(null);
return deviceDetail;
}
public List<Portfolio> getPortfolios() {
return this.portfolios;
}
public void setPortfolios(List<Portfolio> portfolios) {
this.portfolios = portfolios;
}
public Portfolio addPortfolio(Portfolio portfolio) {
getPortfolios().add(portfolio);
portfolio.setUserRegistration(this);
return portfolio;
}
public Portfolio removePortfolio(Portfolio portfolio) {
getPortfolios().remove(portfolio);
portfolio.setUserRegistration(null);
return portfolio;
}
public List<UserDetail> getUserDetails() {
return this.userDetails;
}
public void setUserDetails(List<UserDetail> userDetails) {
this.userDetails = userDetails;
}
public UserDetail addUserDetail(UserDetail userDetail) {
getUserDetails().add(userDetail);
userDetail.setUserRegistration(this);
return userDetail;
}
public UserDetail removeUserDetail(UserDetail userDetail) {
getUserDetails().remove(userDetail);
userDetail.setUserRegistration(null);
return userDetail;
}
public List<UserLoginDetail> getUserLoginDetails() {
return this.userLoginDetails;
}
public void setUserLoginDetails(List<UserLoginDetail> userLoginDetails) {
this.userLoginDetails = userLoginDetails;
}
public UserLoginDetail addUserLoginDetail(UserLoginDetail userLoginDetail) {
getUserLoginDetails().add(userLoginDetail);
userLoginDetail.setUserRegistration(this);
return userLoginDetail;
}
public UserLoginDetail removeUserLoginDetail(UserLoginDetail userLoginDetail) {
getUserLoginDetails().remove(userLoginDetail);
userLoginDetail.setUserRegistration(null);
return userLoginDetail;
}
public UserRoleMaster getUserRoleMaster() {
return this.userRoleMaster;
}
public void setUserRoleMaster(UserRoleMaster userRoleMaster) {
this.userRoleMaster = userRoleMaster;
}
public List<Watch> getWatches() {
return this.watches;
}
public void setWatches(List<Watch> watches) {
this.watches = watches;
}
public Watch addWatch(Watch watch) {
getWatches().add(watch);
watch.setUserRegistration(this);
return watch;
}
public Watch removeWatch(Watch watch) {
getWatches().remove(watch);
watch.setUserRegistration(null);
return watch;
}
}
Please help. Thanks in advance!
With app-engine, you don't need hibernate. Most JPA annotations that you use with hibernate, are natively supported in app-engine. I believe you should not be mixing JDO (javax.jdo) and JPA(javax.persistence).

Updating null value for foreign key

I am working with JPA and I am trying to insert foreign key value its working fine but during modifying it is updating null values..
Please Refer following code
package com.bcits.bfm.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="JOB_CALENDER")
public class JobCalender implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int jobCalenderId;
private int scheduleType;
private String title;
private String description;
private String recurrenceRule;
private String recurrenceException;
private int recurrenceId;
private boolean isAllDay;
private Date start;
private Date end;
private String jobNumber;
private String jobGroup;
private int expectedDays;
private String jobPriority;
private String jobAssets;
private MaintainanceTypes maintainanceTypes;
private MaintainanceDepartment departmentName;
private JobTypes jobTypes;
#Id
#Column(name="JOB_CALENDER_ID")
#SequenceGenerator(name = "JOB_CALENDER_SEQUENCE", sequenceName = "JOB_CALENDER_SEQUENCE")
#GeneratedValue(generator = "JOB_CALENDER_SEQUENCE")
public int getJobCalenderId() {
return jobCalenderId;
}
public void setJobCalenderId(int jobCalenderId ) {
this.jobCalenderId = jobCalenderId ;
}
#Column(name="SCHEDULE_TYPE")
public int getScheduleType() {
return scheduleType;
}
public void setScheduleType(int scheduleType) {
this.scheduleType = scheduleType;
}
#Column(name="START_DATE")
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
#Column(name="END_DATE")
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
#Column(name="Title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="RECURRENCE_RULE")
public String getRecurrenceRule() {
return recurrenceRule;
}
public void setRecurrenceRule(String recurrenceRule) {
this.recurrenceRule = recurrenceRule;
}
#Column(name="IS_ALL_DAY")
public boolean getIsAllDay() {
return isAllDay;
}
public void setIsAllDay(boolean isAllDay) {
this.isAllDay = isAllDay;
}
#Column(name="RECURENCE_EXCEPTION")
public String getRecurrenceException() {
return recurrenceException;
}
public void setRecurrenceException(String recurrenceException) {
this.recurrenceException = recurrenceException;
}
#Column(name="RECURRENCE_ID")
public int getRecurrenceId() {
return recurrenceId;
}
public void setRecurrenceId(int recurrenceId) {
this.recurrenceId = recurrenceId;
}
/*Custom Columns*/
#Column(name = "JOB_NUMBER", nullable = false, length = 45)
public String getJobNumber() {
return this.jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
#Column(name = "JOB_GROUP", nullable = false, length = 45)
public String getJobGroup() {
return this.jobGroup;
}
public void setJobGroup(String jobGroup) {
this.jobGroup = jobGroup;
}
#Column(name = "EXPECTED_DAYS", nullable = false, precision = 11, scale = 0)
public int getExpectedDays() {
return this.expectedDays;
}
public void setExpectedDays(int expectedDays) {
this.expectedDays = expectedDays;
}
#Column(name = "JOB_PRIORITY", nullable = false, length = 45)
public String getJobPriority() {
return this.jobPriority;
}
public void setJobPriority(String jobPriority) {
this.jobPriority = jobPriority;
}
#Column(name = "JOB_ASSETS", nullable = false, length = 4000)
public String getJobAssets() {
return this.jobAssets;
}
public void setJobAssets(String jobAssets) {
this.jobAssets = jobAssets;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_DEPT_ID",referencedColumnName="MT_DP_IT",nullable = false)
public MaintainanceDepartment getMaintainanceDepartment() {
return this.departmentName;
}
public void setMaintainanceDepartment(
MaintainanceDepartment departmentName) {
this.departmentName = departmentName;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_TYPE_ID",referencedColumnName="JT_ID",nullable = false)
public JobTypes getJobTypes() {
return this.jobTypes;
}
public void setJobTypes(JobTypes jobTypes) {
this.jobTypes = jobTypes;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "MAINTAINANCE_TYPE_ID",nullable = false)
public MaintainanceTypes getMaintainanceTypes() {
return this.maintainanceTypes;
}
public void setMaintainanceTypes(MaintainanceTypes maintainanceTypes) {
this.maintainanceTypes = maintainanceTypes;
}
}
And Parent Table Is
package com.bcits.bfm.model;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* MaintainanceTypes entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "MAINTAINANCE_TYPES")
public class MaintainanceTypes implements java.io.Serializable {
private static final long serialVersionUID = 1L;
// Fields
private int mtId;
private String maintainanceType;
private String description;
private Timestamp mtDt;
private String createdBy;
private String lastUpdatedBy;
private Timestamp lastUpdatedDt;
private Set<JobCards> jobCardses = new HashSet<JobCards>(0);
private Set<JobCalender> jobCalenders = new HashSet<JobCalender>(0);
// Constructors
/** default constructor */
public MaintainanceTypes() {
}
/** minimal constructor */
public MaintainanceTypes(int mtId, String maintainanceType, Timestamp mtDt) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.mtDt = mtDt;
}
/** full constructor */
public MaintainanceTypes(int mtId, String maintainanceType,
String description, Timestamp mtDt, String createdBy,
String lastUpdatedBy, Timestamp lastUpdatedDt,
Set<JobCards> jobCardses) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.description = description;
this.mtDt = mtDt;
this.createdBy = createdBy;
this.lastUpdatedBy = lastUpdatedBy;
this.lastUpdatedDt = lastUpdatedDt;
this.jobCardses = jobCardses;
}
// Property accessors
#Id
#Column(name = "MT_ID", unique = true, nullable = false, precision = 11, scale = 0)
#SequenceGenerator(name = "MAINTENANCE_TYPES_SEQ", sequenceName = "MAINTENANCE_TYPES_SEQ")
#GeneratedValue(generator = "MAINTENANCE_TYPES_SEQ")
public int getMtId() {
return this.mtId;
}
public void setMtId(int mtId) {
this.mtId = mtId;
}
#Column(name = "MAINTAINANCE_TYPE", nullable = false, length = 20)
public String getMaintainanceType() {
return this.maintainanceType;
}
public void setMaintainanceType(String maintainanceType) {
this.maintainanceType = maintainanceType;
}
#Column(name = "DESCRIPTION", length = 200)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "MT_DT", nullable = false, length = 11)
public Timestamp getMtDt() {
return this.mtDt;
}
public void setMtDt(Timestamp mtDt) {
this.mtDt = mtDt;
}
#Column(name = "CREATED_BY", length = 45)
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "LAST_UPDATED_BY", length = 45)
public String getLastUpdatedBy() {
return this.lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
#Column(name = "LAST_UPDATED_DT", length = 11)
public Timestamp getLastUpdatedDt() {
return this.lastUpdatedDt;
}
public void setLastUpdatedDt(Timestamp lastUpdatedDt) {
this.lastUpdatedDt = lastUpdatedDt;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCards> getJobCardses() {
return this.jobCardses;
}
public void setJobCardses(Set<JobCards> jobCardses) {
this.jobCardses = jobCardses;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCalender> getJobCalenders() {
return this.jobCalenders;
}
public void setJobCalenders(Set<JobCalender> jobCalenders) {
this.jobCalenders = jobCalenders;
}
}
I am calling below method to Update
public void Update(JobCalender jobCalender) {
update(jobCalender); //update() is generic method
}
public T update(final T t) {
BfmLogger.logger.info("updating "+t+" instance");
try {
T result = this.entityManager.merge(t);
BfmLogger.logger.info("update successful");
return result;
} catch (RuntimeException re) {
BfmLogger.logger.error("update failed", re);
throw re;
}
}
My Controller Code
#RequestMapping(value = "/index/create", method = RequestMethod.POST)
public #ResponseBody List<?> create(#RequestBody Map<String, Object>model,#ModelAttribute JobCalender jobCalender,BindingResult bindingResult, HttpServletRequest request) throws ParseException {
jobCalender.setDescription((String)model.get("description"));
jobCalender.setTitle((String)model.get("title"));
SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-M-dd'T'HH:mm:ss.SSS'Z'");
iso8601.setTimeZone(TimeZone.getTimeZone("UTC"));
jobCalender.setStart(iso8601.parse((String)model.get("start")));
jobCalender.setEnd(iso8601.parse((String)model.get("end")));
jobCalender.setIsAllDay((boolean) model.get("isAllDay"));
jobCalender.setRecurrenceRule((String)model.get("recurrenceRule"));
jobCalender.setRecurrenceException((String)model.get("recurrenceException"));
if(model.get("recurrenceId")!=null)
jobCalender.setRecurrenceId((Integer)model.get("recurrenceId"));
jobCalender.setScheduleType(Integer.parseInt(model.get("scheduleType").toString()));
jobCalender.setJobNumber((String) model.get("jobNumber"));
jobCalender.setDescription((String) model.get("description"));
jobCalender.setJobGroup((String) model.get("jobGroup"));
jobCalender.setMaintainanceDepartment(maintainanceDepartmentService.find(Integer.parseInt(model.get("departmentName").toString())));
jobCalender.setMaintainanceTypes(maintainanceTypesService.find(Integer.parseInt(model.get("maintainanceTypes").toString())));
jobCalender.setJobTypes(jobTypesService.find(Integer.parseInt(model.get("jobTypes").toString())));
jobCalender.setJobPriority((String) model.get("jobPriority"));
String ids="";
#SuppressWarnings("unchecked")
List<Map<String, Object>> listAssets = (ArrayList<Map<String, Object>>) model.get("assetName");// this is what you have already
for (Map<String, Object> map1 :listAssets) {
for (Map.Entry<String, Object> entry : map1.entrySet()) {
if(entry.getKey().equalsIgnoreCase("assetId")){
ids+=entry.getValue()+",";
}
}
}
jobCalender.setJobAssets(ids);
jobCalenderService.Update(jobCalender);
}
while Updating JOB_CALENDER Table it is Adding NULL Value For MAINTAINANCE_TYPE_ID Column
Please Help Me
Thank You
Regards
Manjunath Kotagi

Resources