JpaRepository ManyToMany Deletion problem - java

I have two models: Events and NotificationUser.
An Event can have many Users and a User can have many Events. I build 2 Models.
Event
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
#ElementCollection
private List<Action> actions;
private String description;
#ManyToMany
private List<NotificationUser> notificationUser;
}
NotificationUser
public class NotificationUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String email;
private String name;
}
I can create events and I can create users. I can also delete events but, I cannot delete users. I get the following message:
update or delete on table "notification_user" violates foreign key constraint "fkjuklqmawfcf1ein89djo7945t" on table "event_notification_user"
Detail: Key (id)=(12) is still referenced from table "event_notification_user"
I don't understand the Annotations to set on the models.
Is there a simple way to handle the relations? I don't want to get my repo locked for some simple stuff like deletions. That's the reason why I use JPARepository.
Thanks for your time.

Related

Is this relationship a #OneToMany instance?

I already have two tables:
zip_codes_germany
and
travel_agencies
filled with some data. Where travel_agencies has a composite key from columns name and city and zip_codes_germany has the primary key zip_code.
Let the condition be fulfilled that the city names are the same in both tables. Now one city maps to multiple zip_codes.
What is the best way to make this relationship clear in order to receive the correct list of zip codes when loading a TravelAgency object using hibernate?
I'm thinking of something like this:
#Entity
#Table(name = "travel_agencies")
public class TravelAgency implements Serializable {
private static final long serialVersionUID = -5215122407119218666L;
#Id
#Column(name = "name")
private String name;
#Id
#Column(name = "city")
private String city;
#Column(name = "ceo")
private String ceo;
#OneToMany
#JoinColumn(name = "city")
private Set<ZipCodeArea> zipCodeAreas;
I'm new to hibernate and working with databases in general so I'm not quite sure if it is the correct tool to get what I'm asking for or if I'd better go with something else?
As commented by OH GOD SPIDERS, I do have a many to many relationship here.

OOPS DataBase Design help for Bug tracking application

lets say there are two tables TICKET and USER
table USER(username, password, roles)
Table TICKET(ticketname,users_assigned)
the problem in the TICKET table is how can I have attribute List in table TICKET. can someone guide me on how to make the TICKET table. coz I'm planning to implement the Ticket table with List as a property using java Spring Data JPA ORM.but I don't know how to create tables that go with it
I was thinking maybe have another table TicketUser(username,ticketname). I just want to know if there's a better way to design this. thanks in advance.
Your thinking is correct.
First Step : add an id column to all you tables
second step : create a table TicketUser (userId, ticketId) referencing the respective foreign keys.
Or you can also let jpa create the table for you you just create classes in you code like
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id; // or long
private String name, password, roles;
#OneToMany
private List<Ticket> ticketList;
// constructor, getters, setters, etc.
}
For Ticket class
#Entity
public class Ticket {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id; // or long
private name;
#ManyToOne
private User user;
//Constructor, Getter and Setters, ...
}

Sort by count in spring mvc, for a OneToMany variable

I have two classes in my spring application:
#Entity
#Table(name = "events")
public class Event {
#Id
#GeneratedValue
private long id;
#ManyToOne
#JoinColumn(name = "venue_fk")
private Venue venue;
// Setters, getters...
}
and
#Entity
#Table(name = "venues")
public class Venue {
#Id
#GeneratedValue
private long id;
private String name;
#OneToMany
private Set<Event> events = new HashSet<>();
// Setters, getters...
}
The thing I want to do is to write a method in VenueService that returns Iterable<Venue> and venue objects appear in this Iterable based on how many events they have (DESC) and then venue name(ASC), the more events one venue has, the earlier it appears.
E.g. I have three venues, venueA has 3 events registered with it, venueB has 3 events registered with it, and venueC has 4 events registered with it, then the method findAllVenuesByNoOfEvents() should return Iterable<Venue> in the order venueC, venueA, venueB.
I'm new to spring and I'm really don't know how to do this, thanks in advance.

Lazy Initialization Exception on Initialize a Collection - JPA

I implement a simple SpringMVC application. As models I have Person and Event both get mapped to a H2 database.
For now I am able to store a Person object and an Event object as well. But when I am trying to store a list of Person to my Event object than I always get the exception:
failed to lazily initialize a collection, could not initialize proxy - no Session
My approach so far:
#Entity
public class Event implements Persistable<Long> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String eventName;
#OneToMany(fetch = FetchType.EAGER)
#ElementCollection(targetClass = Member.class)
private List<Person> members = new ArrayList<>();
}
#Entity
public class Person implements Persistable<Long>{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
}
The goal is to select Person objects with a primefaces SelectManyMenu and store them to the List<Person> members of the event. When I add some Person objects to an Event via SQL than the SelectManyMenu pre-selects the added Person objects correctly. But when I select an additional Person object and call save then the exception appears.
First I thought my save-method doesn't work. But it has to work correctly because I am able to save Person objects and Event objects separately (without a Relationship between).
To map properly, you should map members field as #OneToMany(mappedBy = "event", fetch = ...), and add #ManyToOne Event event in your Person class. Also you can be certain about what fetching strategy needed to use by reading fetching strategies document.

Hibernate: Repeated Column in Mapping

So in this example scenario I have an attendance DTO, and a worker DTO, workers in this context are separated by department, and a worker can only ever be inside of one department. It is important to note that Worker {id='123-123-123', department='a'} is different to Worker {id='123-123-123', department='b'}, despite them both sharing the same Id.
I have the following class setup to try and separate functions by id and department
public class IdAndDepartmentPK implements Serializable {
private String id;
private String department;
public IdAndDepartmentPK() {}
...
}
This key class is shared between DTOs that require both the Worker's id and department, below are the two DTOs that are causing a problem.
#Entity
#IdClass(IdAndDepartmentPK.class)
public class AttendencetDto {
#Id private String id; // This is a departmentally unique attendenceId
#Id private String department;
#Column private String workerId;
#JoinColumns({
#JoinColumn(name = "workerId"),
#JoinColumn(name = "department")
})
#ManyToOne(fetch = FetchType.EAGER)
private WorkerDto workerDto;
....
}
#Entity
#IdClass(IdAndDepartmentPK.class)
public class WorkerDto {
#Id
private String id;
#Id
private String department;
...
}
WorkerDto does not need to have knowledge of AttendencetDto, but AttendencetDto, does need to have access to WorkerDto and the other data it contains.
Hibernate complains that fields like workerId should be mapped with insert="false" update="false", but if I was to do this then I wouldn't be able to persist those values to the database.
I essentially want to have those fields available whilst also having the WorkerDto available, is this possible?
You should remove #Column private String workerId; because you already map it by relation to WorkerDto.
If you want to create relation between that you should use setWorkerDto method in your AttendencetDto and just save. After transaction ends you will have your relation in DB.

Categories