I am trying to insert data in oracle DB using spring JPA repositories
I have a hash map which contains all the values which needs to be populated into DB,I am Iterating each value and setting into my Entity class
Basically I have a table which has a composite primary key(NotifiedToId).when I am setting the values ints throwing constraint violation exception.In my logs it is printing all correct values but its not getting inserted,
My Entity class:
#Embeddable
public class TbBamiNotifUserLogPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="NOTIFIED_TO_ID")
private String notifiedToId;
public TbBamiNotifUserLogPK() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getNotifiedToId() {
return this.notifiedToId;
}
public void setNotifiedToId(String notifiedToId) {
this.notifiedToId = notifiedToId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof TbBamiNotifUserLogPK)) {
return false;
}
TbBamiNotifUserLogPK castOther = (TbBamiNotifUserLogPK)other;
return
this.notifRefNo.equals(castOther.notifRefNo)
&& this.notifiedToId.equals(castOther.notifiedToId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.notifRefNo.hashCode();
hash = hash * prime + this.notifiedToId.hashCode();
return hash;
}
}
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="TB_BAMI_NOTIF_USER_LOG")
#NamedQuery(name="TbBamiNotifUserLog.findAll", query="SELECT t FROM TbBamiNotifUserLog t")
public class TbBamiNotifUserLog implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private TbBamiNotifUserLogPK id;
#Column(name="NOTIF_CAT")
private String notifCat;
#Column(name="NOTIFIED_TO_NAME")
private String notifiedToName;
#Column(name="NOTIFIED_TO_ROLE")
private String notifiedToRole;
public TbBamiNotifUserLog() {
}
public TbBamiNotifUserLogPK getId() {
return this.id;
}
public void setId(TbBamiNotifUserLogPK id) {
this.id = id;
}
public String getNotifCat() {
return this.notifCat;
}
public void setNotifCat(String notifCat) {
this.notifCat = notifCat;
}
public String getNotifiedToName() {
return this.notifiedToName;
}
public void setNotifiedToName(String notifiedToName) {
this.notifiedToName = notifiedToName;
}
public String getNotifiedToRole() {
return this.notifiedToRole;
}
public void setNotifiedToRole(String notifiedToRole) {
this.notifiedToRole = notifiedToRole;
}
}
#Entity
#Table(name="TB_BAMI_NOTIFICATION_LOG")
#NamedQuery(name="TbBamiNotificationLog.findAll", query="SELECT t FROM TbBamiNotificationLog t")
public class TbBamiNotificationLog implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="\"ACTION\"")
private String action;
#Column(name="NOTIF_CONTENT")
private String notifContent;
#Column(name="NOTIF_TYPE")
private String notifType;
#Column(name="NOTIFIED_DATE_TIME")
private Timestamp notifiedDateTime;
private String refno;
#Column(name="\"VERSION\"")
private BigDecimal version;
public TbBamiNotificationLog() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getAction() {
return this.action;
}
public void setAction(String action) {
this.action = action;
}
public String getNotifContent() {
return this.notifContent;
}
public void setNotifContent(String notifContent) {
this.notifContent = notifContent;
}
public String getNotifType() {
return this.notifType;
}
public void setNotifType(String notifType) {
this.notifType = notifType;
}
public Timestamp getNotifiedDateTime() {
return this.notifiedDateTime;
}
public void setNotifiedDateTime(Timestamp notifiedDateTime) {
this.notifiedDateTime = notifiedDateTime;
}
public String getRefno() {
return this.refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public BigDecimal getVersion() {
return this.version;
}
public void setVersion(BigDecimal version) {
this.version = version;
}
}
Business Logic:
for (Entry<String, PushNotificationDetails> entry : finalTemplate.entrySet()){
try{
notificationlog.setNotifRefNo("121323");
notificationlog.setRefno(refNum);
notificationlog.setVersion(new BigDecimal(1));
notificationlog.setAction(action);
LOGGER.debug("TEMPLATE TYPE"+entry.getValue().getTemplate_type());
LOGGER.debug("TEMPLATE"+entry.getValue().getTemplate());
notificationlog.setNotifType(entry.getValue().getTemplate_type());
notificationlog.setNotifContent(entry.getValue().getTemplate());
notificationlog.setNotifiedDateTime(notifiedDateTime);
tbBamiNotifyLogRepository.save(notificationlog);
LOGGER.debug("inside if block ::: ");
LOGGER.debug("USERID is: "+entry.getValue().getUserID());
LOGGER.debug("NOTIFCAT is: "+entry.getValue().getNotif_cat());
LOGGER.debug("NOTIFUSER is: "+entry.getValue().getUserName());
LOGGER.debug("NOTIFROLE is: "+entry.getKey());
tbBamiNotifUserLogPK.setNotifiedToId(entry.getValue().getUserID());
tbBamiNotifUserLogPK.setNotifRefNo("121323");
tbBamiNotifUserLog.setId(tbBamiNotifUserLogPK);
LOGGER.debug("GET is: "+tbBamiNotifUserLog.getId().getNotifiedToId());
tbBamiNotifUserLog.setNotifCat(entry.getValue().getNotif_cat());
tbBamiNotifUserLog.setNotifiedToName(entry.getValue().getUserName());
tbBamiNotifUserLog.setNotifiedToRole(entry.getKey());
tbBamiNotifyUserLogRepository.save(tbBamiNotifUserLog);
}
Try to add notificationlog = new TbBamiNotificationLog() in the beginning of your saving for. It could be possible when you try to save the second row but the instance is the same (with id provided during the first save).
Related
I tried to implement custom TiledDataSource for using with paging library. When I used LivePagedListProvider like returns type for my Dao method it worked fine (after table items updating - ui updated automatically).
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC")
LivePagedListProvider<Artist> loadArtists();
But when I try implement custom TiledDataSource for LivePagerListProvider table updates not triggered my observers.
Abstract generic class:
public abstract class PagedNetworkBoundResource<ResultType, RequestType> extends TiledDataSource<ResultType> {
#Override
public int countItems() {
return DataSource.COUNT_UNDEFINED;
}
#Override
public List<ResultType> loadRange(int startPosition, int count) {
fetchFromNetwork(startPosition, count);
return loadFromDb(startPosition, count);
}
#WorkerThread
private void fetchFromNetwork(int startPosition, int count) {
if (createCall(startPosition, count) != null)
try {
Response<RequestType> response = createCall(startPosition, count).execute();
if (response.isSuccessful() && response.code() == 200) {
saveCallResult(response.body());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#WorkerThread
protected abstract void saveCallResult(#NonNull RequestType item);
#WorkerThread
protected abstract List<ResultType> loadFromDb(int startPosition, int count);
#WorkerThread
protected abstract Call<RequestType> createCall(int startPosition, int count);
public LiveData<PagedList<ResultType>> getAsLiveData() {
return new LivePagedListProvider<Integer, ResultType>() {
#Override
protected DataSource<Integer, ResultType> createDataSource() {
return PagedNetworkBoundResource.this;
}
}.create(0, new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(20)
.setInitialLoadSizeHint(20)
.build());
}
}
My dao method for this case:
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC LIMIT (:limit) OFFSET (:offset)")
List<Artist> loadArtists(int offset, int limit);
I update Table.States.PLAY_STATE.
public void updatePlayerState(PlayerStateEntity state){
new Thread(() -> {
dao.deleteState();
dao.insertState(state);
}).run();
}
#Dao
public interface PlayStateDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertState(PlayerStateEntity playEntity);
#Query("DELETE FROM " + Table.States.PLAY_STATE)
void deleteState();
#Query("SELECT * FROM "+Table.States.PLAY_STATE)
PlayerStateEntity getPlayerState();
}
#Entity(tableName = Table.States.PLAY_STATE)
public class PlayerStateEntity extends IdEntity {
#ColumnInfo(name = "album_played_id")
private Long albumPlayedId = -1L;
#ColumnInfo(name = "track_played_id")
private Long trackPlayedId = -1L;
#ColumnInfo(name = "artist_played_id")
private Long artistPlayedId = -1L;
#ColumnInfo(name = "state")
private PlayingState state;
#ColumnInfo(name = "playing_type")
private PlayingType playingType;
public Long getAlbumPlayedId() {
return albumPlayedId;
}
public void setAlbumPlayedId(Long albumPlayedId) {
this.albumPlayedId = albumPlayedId;
}
public Long getTrackPlayedId() {
return trackPlayedId;
}
public void setTrackPlayedId(Long trackPlayedId) {
this.trackPlayedId = trackPlayedId;
}
public Long getArtistPlayedId() {
return artistPlayedId;
}
public void setArtistPlayedId(Long artistPlayedId) {
this.artistPlayedId = artistPlayedId;
}
public PlayingState getState() {
return state;
}
public void setState(PlayingState state) {
this.state = state;
}
public PlayingType getPlayingType() {
return playingType;
}
public void setPlayingType(PlayingType playingType) {
this.playingType = playingType;
}
}
class Artist extends PlayEntity{
private String name;
private String link;
private String picture;
#ColumnInfo(name = "picture_small")
private String pictureSmall;
#ColumnInfo(name = "picture_medium")
private String pictureMedium;
#ColumnInfo(name = "picture_big")
private String pictureBig;
#ColumnInfo(name = "picture_xl")
private String pictureXl;
private Boolean radio;
private String tracklist;
private Integer position;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getPictureSmall() {
return pictureSmall;
}
public void setPictureSmall(String pictureSmall) {
this.pictureSmall = pictureSmall;
}
public String getPictureMedium() {
return pictureMedium;
}
public void setPictureMedium(String pictureMedium) {
this.pictureMedium = pictureMedium;
}
public String getPictureBig() {
return pictureBig;
}
public void setPictureBig(String pictureBig) {
this.pictureBig = pictureBig;
}
public String getPictureXl() {
return pictureXl;
}
public void setPictureXl(String pictureXl) {
this.pictureXl = pictureXl;
}
public Boolean getRadio() {
return radio;
}
public void setRadio(Boolean radio) {
this.radio = radio;
}
public String getTracklist() {
return tracklist;
}
public void setTracklist(String tracklist) {
this.tracklist = tracklist;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
#Override
public boolean isItemPlaying() {
return getId() == getArtistPlayedId().longValue() && getPlayingType() == PlayingType.Artist && getState() == PlayingState.Playing;
}
}
public abstract class PlayEntity extends PlayerStateEntity {
public abstract boolean isItemPlaying();
}
public class ArtistsRepository {
private final ChartArtistDao chartArtistDao;
private final DeezerService deezerService;
#Inject
public ArtistsRepository(ChartArtistDao chartArtistDao, DeezerService deezerService) {
this.chartArtistDao = chartArtistDao;
this.deezerService = deezerService;
}
public LiveData<PagedList<ChartArtistDao.Artist>> getArtist() {
return new PagedNetworkBoundResource<ChartArtistDao.Artist, ModelList<ChartArtistEntity>>() {
#Override
protected void saveCallResult(#NonNull ModelList<ChartArtistEntity> item) {
if (item != null) {
chartArtistDao.saveArtists(item.getItems());
}
}
#Override
protected List<ChartArtistDao.Artist> loadFromDb(int startPosition, int count) {
return chartArtistDao.loadArtists(startPosition, count);
}
#Override
protected Call<ModelList<ChartArtistEntity>> createCall(int startPosition, int count) {
return deezerService.getChartArtist(startPosition, count);
}
}.getAsLiveData();
}
}
For each Artist items I add fields from PlayerStateEntity (not good solution but this easy way to represent state of ui items). After PlayerStateEntity table updates Room should notify about data changes, but doesn't do it.
I understand that Room doesn't know about query what I used, and can't updates my RecyclerView which provide by paging library. But maybe some one knows how to notify Room about tables which I used inside mine DataSource for future triggering ui updates?
The problem was related with custom DataSource realization. When data has changed, LivePagedListProvider should create a new DataSource instance for right ui updating. I used the same instance, so my previous solution is not right.
I have an entity question and an entity test with ManyToMany relationship between the two entitie.
when I want to view the questions of a test this error is occurred.
failed to lazily initialize a collection of role:
tn.esen.entities.Test.questions, could not initialize proxy - no Session
this is the JPA implementation of the two entities.
Question:
package tn.esen.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
#Entity
public class Question implements Serializable {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contenu == null) ? 0 :
contenu.hashCode());
result = prime * result + ((dateCreation == null) ? 0 :
dateCreation.hashCode());
result = prime * result + ((niveauDeDifficulte == null) ? 0 :
niveauDeDifficulte.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Question other = (Question) obj;
if (contenu == null) {
if (other.contenu != null)
return false;
} else if (!contenu.equals(other.contenu))
return false;
if (dateCreation == null) {
if (other.dateCreation != null)
return false;
} else if (!dateCreation.equals(other.dateCreation))
return false;
if (niveauDeDifficulte == null) {
if (other.niveauDeDifficulte != null)
return false;
} else if (!niveauDeDifficulte.equals(other.niveauDeDifficulte))
return false;
return true;
}
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_question")
private int id;
private String contenu;
private String niveauDeDifficulte;
private Date dateCreation;
#OneToMany(mappedBy="question",fetch = FetchType.EAGER)
private Collection <Reponse> reponses;
#ManyToOne
private Categorie categorie;
#ManyToOne
private Administrateur administrateur;
#ManyToMany(mappedBy = "questions",fetch = FetchType.EAGER)
private Collection<Test> tests;
public Question(){
super();
}
#Override
public String toString() {
return "Question [id=" + id + ", contenu=" + contenu + ",
niveauDeDifficulte=" + niveauDeDifficulte + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
public String getNiveauDeDifficulte() {
return niveauDeDifficulte;
}
public void setNiveauDeDifficulte(String niveauDeDifficulte) {
this.niveauDeDifficulte = niveauDeDifficulte;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Collection<Reponse> getReponses() {
return reponses;
}
public void setReponses(Collection<Reponse> reponses) {
this.reponses = reponses;
}
public Categorie getCategorie() {
return categorie;
}
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
public Administrateur getAdministrateur() {
return administrateur;
}
public void setAdministrateur(Administrateur administrateur) {
this.administrateur = administrateur;
}
public Collection<Test> getTest() {
return tests;
}
public void setTest(Collection<Test> tests) {
this.tests = tests;
}
public Question(String contenu, String niveauDeDifficulte, Date
dateCreation) {
super();
this.contenu = contenu;
this.niveauDeDifficulte = niveauDeDifficulte;
this.dateCreation = dateCreation;
}
Test:
package tn.esen.entities;
#Entity
public class Test implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String duree;
private String typeDePreparation;
private String lieu;
private int nbrQuestionFacile;
private int nbrQuestionMoyen;
private int nbrQuestionDifficle;
#OneToMany(mappedBy = "test")
private Collection<Resultat> resultats;
#ManyToMany
private Collection<Question> questions;
#ManyToOne
private ResponsableTechnique responsableTechnique;
public Test() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDuree() {
return duree;
}
public void setDuree(String duree) {
this.duree = duree;
}
public Collection<Question> getQuestions() {
return questions;
}
public void setQuestions(Collection<Question> questions) {
this.questions = questions;
}
public Test(String duree, String typeDePreparation, String lieu, int
nbrQuestionFacile, int nbrQuestionMoyen,
int nbrQuestionDifficle) {
super();
this.duree = duree;
this.typeDePreparation = typeDePreparation;
this.lieu = lieu;
this.nbrQuestionFacile = nbrQuestionFacile;
this.nbrQuestionMoyen = nbrQuestionMoyen;
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public ResponsableTechnique getRésponsableTechnique() {
return responsableTechnique;
}
public void setRésponsableTechnique(ResponsableTechnique
résponsableTechnique) {
this.responsableTechnique = résponsableTechnique;
}
public String getTypeDePreparation() {
return typeDePreparation;
}
public void setTypeDePreparation(String typeDePreparation) {
this.typeDePreparation = typeDePreparation;
}
public String getLieu() {
return lieu;
}
public void setLieu(String lieu) {
this.lieu = lieu;
}
public int getNbrQuestionFacile() {
return nbrQuestionFacile;
}
public void setNbrQuestionFacile(int nbrQuestionFacile) {
this.nbrQuestionFacile = nbrQuestionFacile;
}
public int getNbrQuestionMoyen() {
return nbrQuestionMoyen;
}
public void setNbrQuestionMoyen(int nbrQuestionMoyen) {
this.nbrQuestionMoyen = nbrQuestionMoyen;
}
public int getNbrQuestionDifficle() {
return nbrQuestionDifficle;
}
public void setNbrQuestionDifficle(int nbrQuestionDifficle) {
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public Collection<Resultat> getResultats() {
return resultats;
}
public void setRésultats(Collection<Resultat> resultats) {
this.resultats = resultats;
}
}
}
When you get Test and access Test.questions later, after leaving the transaction, you will get a lazy initialization exception when the Test entity is detached and questions has not been initialized/fetched yet. You can either do a specific fetch, or depending on your configuration, you can call Test.getQuestions().size() before you exit the transaction.
References: How to solve lazy initialization exception using JPA and Hibernate as provider
LazyInitializationException in JPA and Hibernate
Hibernate LazyInitializationException using Spring CrudRepository
I'm having trouble trying to understand how realm.io persist/save objects.
I have 3 Objects (Inventory, InventoryItem and Product);
When I create a Inventory containing InventoryItems it works fine until i close the app. When i re-open the app all InventoryItems loses the reference to Product and start to show "null" instead.
Strange thing is all other attributes like Inventory reference to InventoryItem is persisted fine. Just problem with Products.
this is how i'm trying to do:
Model
Product
public class Product extends RealmObject {
#PrimaryKey
private String id;
#Required
private String description;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
}
Inventory
public class Inventory extends RealmObject {
#PrimaryKey
private String id;
#Required
private String type;
#Required
private Date createdAt;
#Required
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
private RealmList<InventoryItem> listItems;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public RealmList<InventoryItem> getListItems() {
return listItems;
}
public void setListItems(RealmList<InventoryItem> listItems) {
this.listItems = listItems;
}
}
InventoryItem
public class InventoryItem extends RealmObject {
#PrimaryKey
private String idItem;
private Inventory inventory;
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
private Date expirationDate;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
private int qtdDiscard;
public String getIdItem() {
return idItem;
}
public void setIdItem(String idItem) {
this.idItem = idItem;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
public int getQtdDiscard() {
return qtdDiscard;
}
public void setQtdDiscard(int qtdDiscard) {
this.qtdDiscard = qtdDiscard;
}
}
and finally one of the millions ways i tried to persist
realm.beginTransaction();
Inventory inventory = realm.createObject(Inventory.class);
inventory.setId(id);
inventory.setCreatedAt(new DateTime().toDate());
if (radioGroup.getCheckedRadioButtonId() == R.id.rbInventario) {
inventory.setType("Inventário");
} else {
inventory.setType("Validade");
}
inventory.setStatus("Aberto");
RealmList<InventoryItem> inventoryItems = new RealmList<>();
RealmResults<Product> productsRealmResults = realm.allObjects(Product.class);
for (int i = 1; i <= productsRealmResults.size(); i++) {
InventoryItem item = realm.createObject(InventoryItem.class);
item.setIdProduct(productsRealmResults.get(i - 1).getId() + " - " + productsRealmResults.get(i - 1).getDescription());
item.setProduct(productsRealmResults.get(i - 1));
item.setIdItem(i + "-" + id);
item.setInventory(inventory);
item = realm.copyToRealmOrUpdate(item);
item = realm.copyToRealmOrUpdate(item);
inventoryItems.add(item);
}
inventory.setListItems(inventoryItems);
realm.copyToRealmOrUpdate(inventory);
realm.commitTransaction();
I already looked trough some answers here like this one:
stack answer
and the Java-examples (person, dog, cat)
provided with the API
but I can't understand how to properly insert this.
The problem is that you are setting a list of InventoryItem elements which are not added to the Realm database.
Change InventoryItem item = new InventoryItem(); to InventoryItem item = realm.createObject(InventoryItem.class);
Also, the inventoryItems themselves aren't stored in Realm db. Add realm.copyToRealmOrUpdate(inventoryItems) after the loop.
I have a table called conclusion and it has a relationship with table comments.
When i am adding conclusion and comments at the same time, Conclusion is being inserted but child getting conclusion id as null by which i'm getting violation of not null constraint.
My transaction roll backs conclusion also not inserted.
So please tell me how to insert parent and child at once.
my entities are
Conclusion Entity
#Entity
#Table(name="olm_anlys_cncln")
public class OlmAnalysisConclusion implements Serializable {
private static final long serialVersionUID = 1L;
private Long conclusionId;
private String concludedBy;
private Timestamp concludedTime;
private String conclusion;
private Timestamp discussionEndTime;
private String discussionActive;
private Timestamp discussionStartTime;
private Integer tntId;
private OlmAnalysis olmAnly;
private OlmAnalysisCategory olmAnlysCatgMstr;
private OlmAnalysisCause olmAnlysCauseMstr;
private List<OlmInvsgDiscussionComment> olmInvsgDiscnCmnts;
public OlmAnalysisConclusion() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="olm_anlys_cncln_id")
public Long getConclusionId() {
return this.conclusionId;
}
public void setConclusionId(Long conclusionId) {
this.conclusionId = conclusionId;
}
#Column(name="cncld_by")
public String getConcludedBy() {
return this.concludedBy;
}
public void setConcludedBy(String concludedBy) {
this.concludedBy = concludedBy;
}
#Column(name="cncld_time")
public Timestamp getConcludedTime() {
return this.concludedTime;
}
public void setConcludedTime(Timestamp concludedTime) {
this.concludedTime = concludedTime;
}
#Column(name="cncln")
public String getConclusion() {
return this.conclusion;
}
public void setConclusion(String conclusion) {
this.conclusion = conclusion;
}
#Column(name="discn_end_time")
public Timestamp getDiscussionEndTime() {
return this.discussionEndTime;
}
public void setDiscussionEndTime(Timestamp discussionEndTime) {
this.discussionEndTime = discussionEndTime;
}
#Column(name="discn_flag")
public String getDiscussionActive() {
return this.discussionActive;
}
public void setDiscussionActive(String discussionActive) {
this.discussionActive = discussionActive;
}
#Column(name="discn_strt_time")
public Timestamp getDiscussionStartTime() {
return this.discussionStartTime;
}
public void setDiscussionStartTime(Timestamp discussionStartTime) {
this.discussionStartTime = discussionStartTime;
}
#Column(name="tnt_id")
public Integer getTntId() {
return this.tntId;
}
public void setTntId(Integer tntId) {
this.tntId = tntId;
}
//bi-directional many-to-one association to OlmAnalysis
#ManyToOne
#JoinColumn(name="anlys_id")
public OlmAnalysis getOlmAnly() {
return this.olmAnly;
}
public void setOlmAnly(OlmAnalysis olmAnly) {
this.olmAnly = olmAnly;
}
//bi-directional many-to-one association to OlmAnalysisCategory
#ManyToOne
#JoinColumn(name="catg_id")
public OlmAnalysisCategory getOlmAnlysCatgMstr() {
return this.olmAnlysCatgMstr;
}
public void setOlmAnlysCatgMstr(OlmAnalysisCategory olmAnlysCatgMstr) {
this.olmAnlysCatgMstr = olmAnlysCatgMstr;
}
//bi-directional many-to-one association to OlmAnalysisCause
#ManyToOne
#JoinColumn(name="cause_id")
public OlmAnalysisCause getOlmAnlysCauseMstr() {
return this.olmAnlysCauseMstr;
}
public void setOlmAnlysCauseMstr(OlmAnalysisCause olmAnlysCauseMstr) {
this.olmAnlysCauseMstr = olmAnlysCauseMstr;
}
//bi-directional many-to-one association to OlmInvsgDiscussionComment
#OneToMany(fetch=FetchType.EAGER,mappedBy="olmAnlysCncln",cascade=CascadeType.ALL)
public List<OlmInvsgDiscussionComment> getOlmInvsgDiscnCmnts() {
return this.olmInvsgDiscnCmnts;
}
public void setOlmInvsgDiscnCmnts(List<OlmInvsgDiscussionComment> olmInvsgDiscnCmnts) {
this.olmInvsgDiscnCmnts = olmInvsgDiscnCmnts;
}
public OlmInvsgDiscussionComment addOlmInvsgDiscnCmnt(OlmInvsgDiscussionComment olmInvsgDiscnCmnt) {
getOlmInvsgDiscnCmnts().add(olmInvsgDiscnCmnt);
olmInvsgDiscnCmnt.setOlmAnlysCncln(this);
return olmInvsgDiscnCmnt;
}
public OlmInvsgDiscussionComment removeOlmInvsgDiscnCmnt(OlmInvsgDiscussionComment olmInvsgDiscnCmnt) {
getOlmInvsgDiscnCmnts().remove(olmInvsgDiscnCmnt);
olmInvsgDiscnCmnt.setOlmAnlysCncln(null);
return olmInvsgDiscnCmnt;
}
}
Comment Entity
#Entity
#Table(name="olm_invsg_discn_cmnt")
public class OlmInvsgDiscussionComment implements Serializable {
private static final long serialVersionUID = 1L;
private Long commentId;
private String comment;
private Timestamp commentTime;
private String commentedBy;
private Integer tenentId;
private OlmAnalysisConclusion olmAnlysCncln;
private Set<OlmInvsgCommentAttachment> olmInvsgDiscnCmntAtmnts;
public OlmInvsgDiscussionComment() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="olm_invsg_discn_cmnt_id")
public Long getCommentId() {
return this.commentId;
}
public void setCommentId(Long commentId) {
this.commentId = commentId;
}
#Column(name="cmnt")
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#Column(name="cmnt_time")
public Timestamp getCommentTime() {
return this.commentTime;
}
public void setCommentTime(Timestamp commentTime) {
this.commentTime = commentTime;
}
#Column(name="cmntd_by")
public String getCommentedBy() {
return this.commentedBy;
}
public void setCommentedBy(String commentedBy) {
this.commentedBy = commentedBy;
}
#Column(name="tnt_id")
public Integer getTenentId() {
return this.tenentId;
}
public void setTenentId(Integer tenentId) {
this.tenentId = tenentId;
}
//bi-directional many-to-one association to OlmAnalysisConclusion
#ManyToOne(fetch=FetchType.EAGER, optional=false)
#JoinColumn(name="cncln_id")
public OlmAnalysisConclusion getOlmAnlysCncln() {
return this.olmAnlysCncln;
}
public void setOlmAnlysCncln(OlmAnalysisConclusion olmAnlysCncln) {
this.olmAnlysCncln = olmAnlysCncln;
}
//bi-directional many-to-one association to OlmInvsgCommentAttachment
#OneToMany(fetch=FetchType.EAGER,mappedBy="olmInvsgDiscnCmnt",cascade=CascadeType.ALL)
public Set<OlmInvsgCommentAttachment> getOlmInvsgDiscnCmntAtmnts() {
return this.olmInvsgDiscnCmntAtmnts;
}
public void setOlmInvsgDiscnCmntAtmnts(Set<OlmInvsgCommentAttachment> olmInvsgDiscnCmntAtmnts) {
this.olmInvsgDiscnCmntAtmnts = olmInvsgDiscnCmntAtmnts;
}
public OlmInvsgCommentAttachment addOlmInvsgDiscnCmntAtmnt(OlmInvsgCommentAttachment olmInvsgDiscnCmntAtmnt) {
getOlmInvsgDiscnCmntAtmnts().add(olmInvsgDiscnCmntAtmnt);
olmInvsgDiscnCmntAtmnt.setOlmInvsgDiscnCmnt(this);
return olmInvsgDiscnCmntAtmnt;
}
public OlmInvsgCommentAttachment removeOlmInvsgDiscnCmntAtmnt(OlmInvsgCommentAttachment olmInvsgDiscnCmntAtmnt) {
getOlmInvsgDiscnCmntAtmnts().remove(olmInvsgDiscnCmntAtmnt);
olmInvsgDiscnCmntAtmnt.setOlmInvsgDiscnCmnt(null);
return olmInvsgDiscnCmntAtmnt;
}
}
The most probable reason for the join column being null in your table is that the olmAnlysCncln field is null in the OlmInvsgDiscussionComment entity you're trying to persist. That's the owner side of the bidirectional association. You MUST initialize it if you want Hibernate to set something in the corresponding column. Adding the comment to the conclusion is not sufficient.
Side note: vowels are accepted, and even recommented, in property names. You should be able to pronounce a property name. olmInvsgDiscnCmntAtmnts is unpronouceable and unreadable. Use proper English names.
I am pretty new to Hibernate and JPA implementation in Spring, so basically have set up a MySQL 5 database which maps to the domain objects below.
I am trying to search for Location on the Company_Details table but I can't figure out how to search the class Product_Details for Product_Name at the same time
If anyone could help that would be great.
Company_Details
#Entity
public class Company_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3336251433829975771L;
#Id
#GeneratedValue
private Integer Id;
private String Company;
private String Address_Line_1;
private String Address_Line_2;
private String Postcode;
private String County;
private String Country;
private String Mobile_Number;
private String Telephone_Number;
private String URL;
private String Contact;
private String Logo_URL;
private double Amount_Overall;
private double Amount_Paid;
private Timestamp Date_Joined;
private int Account_Details;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Company_Id")
private List<Product_Details> products;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getCompany() {
return Company;
}
public void setCompany(String company) {
Company = company;
}
public String getAddress_Line_1() {
return Address_Line_1;
}
public void setAddress_Line_1(String address_Line_1) {
Address_Line_1 = address_Line_1;
}
public String getAddress_Line_2() {
return Address_Line_2;
}
public void setAddress_Line_2(String address_Line_2) {
Address_Line_2 = address_Line_2;
}
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
public String getCounty() {
return County;
}
public void setCounty(String county) {
County = county;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getMobile_Number() {
return Mobile_Number;
}
public void setMobile_Number(String mobile_Number) {
Mobile_Number = mobile_Number;
}
public String getTelephone_Number() {
return Telephone_Number;
}
public void setTelephone_Number(String telephone_Number) {
Telephone_Number = telephone_Number;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getLogo_URL() {
return Logo_URL;
}
public void setLogo_URL(String logo_URL) {
Logo_URL = logo_URL;
}
public double getAmount_Overall() {
return Amount_Overall;
}
public void setAmount_Overall(double amount_Overall) {
Amount_Overall = amount_Overall;
}
public double getAmount_Paid() {
return Amount_Paid;
}
public void setAmount_Paid(double amount_Paid) {
Amount_Paid = amount_Paid;
}
public Timestamp getDate_Joined() {
return Date_Joined;
}
public void setDate_Joined(Timestamp date_Joined) {
Date_Joined = date_Joined;
}
public int getAccount_Details() {
return Account_Details;
}
public void setAccount_Details(int account_Details) {
Account_Details = account_Details;
}
public List<Product_Details> getProducts() {
return products;
}
public void setProducts(List<Product_Details> products) {
this.products = products;
}
Product_Details
#Entity
public class Product_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6477618197240654478L;
#Id
#GeneratedValue
private Integer Id;
private Integer Company_Id;
private String Product_Name;
private String Description;
private String Main_Photo_URL;
private String Other_Photo_URLS;
private Integer Total_Bookings;
private double Average_Rating;
private Integer Number_Of_Slots;
private Integer Time_Per_Slot;
private double Price_Per_Slot;
private String Monday_Open;
private String Tuesday_Open;
private String Wednesday_Open;
private String Thursday_Open;
private String Friday_Open;
private String Saturday_Open;
private String Sunday_Open;
private String Dates_Closed;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public Integer getCompany_Id() {
return Company_Id;
}
public void setCompany_Id(Integer company_Id) {
Company_Id = company_Id;
}
public String getProduct_Name() {
return Product_Name;
}
public void setProduct_Name(String product_Name) {
Product_Name = product_Name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getMain_Photo_URL() {
return Main_Photo_URL;
}
public void setMain_Photo_URL(String main_Photo_URL) {
Main_Photo_URL = main_Photo_URL;
}
public String getOther_Photos_URLS() {
return Other_Photo_URLS;
}
public void setOther_Photos_URLS(String other_Photo_URLS) {
Other_Photo_URLS = other_Photo_URLS;
}
public Integer getTotal_Bookings() {
return Total_Bookings;
}
public void setTotal_Bookings(Integer total_Bookings) {
Total_Bookings = total_Bookings;
}
public double getAverage_Rating() {
return Average_Rating;
}
public void setAverage_Rating(double average_Rating) {
Average_Rating = average_Rating;
}
public Integer getNumber_Of_Slots() {
return Number_Of_Slots;
}
public void setNumber_Of_Slots(Integer number_Of_Slots) {
Number_Of_Slots = number_Of_Slots;
}
public Integer getTime_Per_Slot() {
return Time_Per_Slot;
}
public void setTime_Per_Slot(Integer time_Per_Slot) {
Time_Per_Slot = time_Per_Slot;
}
public double getPrice_Per_Slot() {
return Price_Per_Slot;
}
public void setPrice_Per_Slot(double price_Per_Slot) {
Price_Per_Slot = price_Per_Slot;
}
public String getMonday_Open() {
return Monday_Open;
}
public void setMonday_Open(String monday_Open) {
Monday_Open = monday_Open;
}
public String getTuesday_Open() {
return Tuesday_Open;
}
public void setTuesday_Open(String tuesday_Open) {
Tuesday_Open = tuesday_Open;
}
public String getWednesday_Open() {
return Wednesday_Open;
}
public void setWednesday_Open(String wednesday_Open) {
Wednesday_Open = wednesday_Open;
}
public String getThursday_Open() {
return Thursday_Open;
}
public void setThursday_Open(String thursday_Open) {
Thursday_Open = thursday_Open;
}
public String getFriday_Open() {
return Friday_Open;
}
public void setFriday_Open(String friday_Open) {
Friday_Open = friday_Open;
}
public String getSaturday_Open() {
return Saturday_Open;
}
public void setSaturday_Open(String saturday_Open) {
Saturday_Open = saturday_Open;
}
public String getSunday_Open() {
return Sunday_Open;
}
public void setSunday_Open(String sunday_Open) {
Sunday_Open = sunday_Open;
}
public String getDates_Closed() {
return Dates_Closed;
}
public void setDates_Closed(String dates_Closed) {
Dates_Closed = dates_Closed;
}
}
#Service
public class ProductServiceImpl implements ProductService{
private final static Logger LOG = Logger.getLogger(ProductServiceImpl.class.getName());
#PersistenceContext
EntityManager em;
#Transactional
public List<Company_Details> search(Search search) {
LOG.info("Entering search method");
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Company_Details> c = builder.createQuery(Company_Details.class);
Root<Company_Details> companyRoot = c.from(Company_Details.class);
c.select(companyRoot);
c.where(builder.equal(companyRoot.get("County"),search.getLocation()));
return em.createQuery(c).getResultList();
}
}
You need two criteria: criteria on the Company_Details class
And criteria on the Product_Details class
Then
Criteria crit1 = session.createCriteria(Company_Details.class);
crit1.add(restriction)
Criteria crit2 = crit1.createCriteria("products");
crit2.add(restriction)
// Then query crit1
List results = crit1.list();