How can i ignore a annotation of cache on a Domain? - spring

I have two tables, table A and table B.
#Entity
#Table(name = "A")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class A implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#NotNull
#Size(max = 250)
#Column(name = "name", length = 250, nullable = false, unique = true)
private String name;
#OneToMany(mappedBy = "aitems")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<B> bItems = new HashSet<>()
#Entity
#Table(name = "B")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class B implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#NotNull
#Size(max = 250)
#Column(name = "name", length = 250, nullable = false)
private String name;
#ManyToOne
#JsonIgnoreProperties("bItems")
private A aItems;
I can create post request for table A and Table B, but if i create a post for A , and after a post for B with relation to the item A that was before created , i want to be able do send a Get request to A and see the B item, but i can only seem them after i reboot my aplication, because when i do the first A post it's stays on cache without any B item.
How can i ignore this without removing it from the domain.
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

Depending on your implementation, you may be able to take advantage of #CacheEvict. Check out the docs, they show you how you can evict A's cache when a POST to B occurs.
Hope this helps

Related

EntityNotFoundException when using #Cacheable

On my application I have multiple entities like:
#Entity
#Data
#Builder
#ToString(of = {"id", "code", "nameContentType", "observations"})
#EqualsAndHashCode(exclude = "room")
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "desk")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Desk implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "code")
private String code;
#Lob
#Column(name = "name")
private byte[] name;
#Column(name = "name_content_type")
private String nameContentType;
#Column(name = "observations")
private String observations;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(unique = true)
private Coordinates coordinates;
#OneToMany(mappedBy = "desk")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<Reservation> reservations = new HashSet<>();
#ManyToOne
#JoinColumn(name = "room_id", insertable = false, updatable = false)
#JsonIgnoreProperties(value = "desks", allowSetters = true)
private Room room;
}
All relationships represented with a collection are cached with #Cache(usage = CacheConcurrencyStrategy.READ_WRITE).
When I delete some records of related Entities I get:
javax.persistence.EntityNotFoundException: Unable to find com.**.domain.Reservation with id ***
I don't know if I have to make any extra adjustments to my cache settings or how to debug the problem
Are you sure you updated Hibernate to the latest version 5.4.32.Final? If so, and you still have the problem, please create an issue in the issue tracker(https://hibernate.atlassian.net) with a test case(https://github.com/hibernate/hibernate-test-case-templates/blob/master/orm/hibernate-orm-5/src/test/java/org/hibernate/bugs/JPAUnitTestCase.java) that reproduces the issue.

How do I map an #OneToMany and #ManyToOne relationship properly so that I can save and update the #OneToMany side with or without the #ManyToOne side

I have an app with Angular front end and Spring backend. The two classes in question here are (backend):
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "tournament_games")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class TournamentGame {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "code", foreignKey = #ForeignKey(name = "code_fk"))
private TournamentCode code;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "type", foreignKey = #ForeignKey(name = "game_type_fk"))
private GameType type;
#Column(name = "home_score")
private int home_score;
#Column(name = "away_score")
private int away_score;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "result_type", foreignKey = #ForeignKey(name = "result_type_fk"))
private ResultType result_type;
#Column(name = "status")
private boolean status;
#Column(name = "round")
private int round;
#Column(name = "locked")
private boolean locked;
#OneToMany(mappedBy = "game", fetch = FetchType.EAGER)
private List<TournamentGamesPlayers> players = new ArrayList<>();
}
and
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "tournament_games_players")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "game")
public class TournamentGamesPlayers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "tournament_game_id")
private TournamentGame game;
#Id
#ManyToOne
#JoinColumn(name = "playerid")
private Player player;
#Column(name = "home")
private boolean home;
}
I need help figuring out how to persist the List<TournamentGamesPlayers> when I save and/or update a TournamentGame object. I generate 45 games. The first 30 games have known players, and so I set them before saving. The last 15 do not have entries for the TournamentGamesPlayers join table, because I need to add them later.
I am able to get some results with CascadeType.ALL on the #OneToMany side when I initially generate the games, but it fails when I try to update a game with a seemingly infinite recursion/stack overflow.
If I omit any cascade type, the games side get generated, but the join table #ManyToOne side does not get entered.
I ended up just putting the players back into the game table to make my life easier.
try putting CascadeType.MERGE, CascadeType.ALL "delete parent and orphans" (JPA CascadeType.ALL does not delete orphans).
Also, defining the relationship as EAGER and not ignoring the JSON property can have problems. I would add #JsonIgnore to one of the parts of the relationship

Can not find entity of the oneToOne relation

public class Maintenance implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "maintenance_issue_mod",
joinColumns = #JoinColumn(name = "maintenance_id"),
inverseJoinColumns = #JoinColumn(name = "issue_mod_id"))
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<IssueMod> issueMod = new HashSet<>();
#OneToOne(fetch = FetchType.LAZY, targetEntity = COrder.class)
#NotNull
#NotFound(
action = NotFoundAction.IGNORE)
#JoinColumn(name="c_order_id", nullable = false, insertable = false,
updatable = false)
private COrder cOrder;
#OneToOne
#JoinColumn(name = "invoice_id")
private Invoice invoice;
#OneToOne
#JoinColumn(name = "referred_invoice_id")
private Invoice referredInvoice;
getter and setter
this is the Maintenance class and relation of the Maintenance and COrder is OneToOne .
this is corder class
public class COrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#CreatedDate
#NotNull
#Column(name = "created", nullable = false)
private Instant created = Instant.now();
#Size(max = 255)
#NotNull
#Column(name = "order_number", length = 255, nullable = false, unique = true)
private String orderNumber;
Maintenance maintenance = maintenanceRepository.findById(maintenanceInvoiceDTO.getMaintenanceId());
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " +maintenance);
COrder currentOrder = cOrderRepository.findOneById(maintenance.getcOrder().getId());
in the service to find the maintenance through the maintenanceId
then we get the following error
'Unable to find in.bsrnetwork.ctrack.domain.COrder with id 1'
but the corder id 1 is present in the the corder table

Hibernate session closed with large volume

I try to retrieve the data from a table linked to a parent table with the following entities:
Entity
#Table(name = "REF_BONJOUR_UNITE")
#NamedQuery(name = "UniteEntity.findAll", query = "SELECT u FROM UniteEntity u")
public class UniteEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "CODE_UNITE")
private String codeUnite;
// bi-directional many-to-one association to Insee
#OneToMany(mappedBy = "refBonjourUnite", fetch = FetchType.LAZY, cascade = CascadeType.MERGE )
private List<Insee> refBonjourInsees;
and the daughter entity :
#Entity
#Table(name = "REF_BONJOUR_INSEE")
#NamedQuery(name = "Insee.findAll", query = "SELECT i FROM Insee i")
public class Insee implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private InseePK id;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_FIN_INSEE_GEO")
#IsOracleDate
private Date dateFinInseeGeo;
private String tylemt;
// bi-directional many-to-one association to UniteEntity
#ManyToOne
#JoinColumn(name = "CODE_UNITE_FK", insertable = false, updatable = false)
private UniteEntity refBonjourUnite;
When i try to access this list with a large amount of data, i get a failed to lazily initialize a collection of role, here exactly :
List<Insee> codeInsees = unite.getRefBonjourInsees();
Insee codeInsee = codeInsees.get(0)

one to many mapping in hibernate for a messaging service

I have two JPA entities: User and Message.
Each Message has one sender and one receiver of type User. And on the other side each User has two sets of type Message: inbox and outbox.
Message:
#Entity
#Table(name = "messages")
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "seq")
#SequenceGenerator(name = "seq", sequenceName = "MESSAGES_SEQ")
#Column(name = "ID", insertable = false, updatable = false)
private int id;
#ManyToOne
#JoinColumn(name = "SENDER")
private User sender;
#ManyToOne
#JoinColumn(name = "RECEIVER")
private User receiver;
private String subject, content;
private Date sdate;
//getters and setters
}
All the properties which not being mapped with an annotation has he same name as the columns in database and are automatically mapped by JPA.
User:
#Entity
#Table(name = "users")
public class User {
#Column(name = "USERNAME")
private String username;
#Column(name = "PASSWORD")
private String pass;
#Column(name = "EMAIL")
private String email;
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "seq")
#SequenceGenerator(name = "seq", sequenceName = "USERS_SEQ")
#Column(name = "ID", insertable = false, updatable = false)
private int id;
#OneToMany(mappedBy = "uploader")
private Set<Book> books;
#OneToMany(mappedBy = "receiver")
private Set<Message> inbox;
#OneToMany(mappedBy = "sender")
private Set<Message> outbox;
//getters and setters
}
The problem is, when I select an User from Oracle database, then the inbox property is empty. How is this caused and how can I solve it?

Resources