I have my entity class called employee and I want to soft delete my entity when I select and press delete button. I can able to select multiple employees as well, So in Java I used List of employee Entities and I want to update whole list into database table if I use merge of entityManager I can able to update only one row i.e only one entity so how do I solve this problem?
Here is some sample code.
#Entity
#Table(name="EmpInfo",schema="Auth")
public class EmpInfo{
#Id
#Column(name="EmpId")
private String userId;
#Column(name="EmailId")
private String emailId;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="MiddleName")
private String middleName;
#Column(name="UserAttributes")
private String userAttributes;
#Column(name="AddedDate")
private Timestamp addedDate;
#Column(name="ModifiedDate")
private Timestamp modifiedDate;
#Column(name="LastLoginDate")
private Timestamp lastLoginDate;
#Column(name="IsDeleted")
private int isDeleted;
#Column(name="AddedBy")
private String addedBy;
#Transient
private String addedByEmailId;
public String getAddedByEmailId() {
return addedByEmailId;
}
public void setAddedByEmailId(String addedByEmailId) {
this.addedByEmailId = addedByEmailId;
}
public EmpInfo() {
// TODO Auto-generated constructor stub
}
public EmpInfo(EmpInfo uInfo){
super();
this.userId=uInfo.userId;
this.emailId=uInfo.emailId;
this.firstName=uInfo.firstName;
this.lastName=uInfo.lastName;
this.middleName=uInfo.middleName;
this.userAttributes=uInfo.userAttributes;
this.addedDate=uInfo.addedDate;
this.lastLoginDate=uInfo.lastLoginDate;
this.modifiedDate=uInfo.modifiedDate;
this.addedBy=uInfo.addedBy;
this.roles=uInfo.roles;
}
public List<RoleName> getRoles() {
return roles;
}
public void setRoles(List<RoleName> roles) {
this.roles = roles;
}
public int getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(int isDeleted) {
this.isDeleted = isDeleted;
}
public Date getAddedDate() {
return addedDate;
}
public void setAddedDate(Timestamp addedDate) {
this.addedDate = addedDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Timestamp modifiedDate) {
this.modifiedDate = modifiedDate;
}
public Date getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(Timestamp lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getUserAttributes() {
return userAttributes;
}
public void setUserAttributes(String userAttributes) {
this.userAttributes = userAttributes;
}
public String getAddedBy() {
return addedBy;
}
public void setAddedBy(String addedBy) {
this.addedBy = addedBy;
}
#Override
public String toString() {
return "EmpInfo [userId=" + userId + ", emailId=" + emailId + ", firstName=" + firstName + ", lastName="
+ lastName + ", middleName=" + middleName + ", userAttributes=" + userAttributes + ", addedDate="
+ addedDate + ", modifiedDate=" + modifiedDate + ", lastLoginDate=" + lastLoginDate + ", isDeleted="
+ isDeleted + ", addedBy=" + addedBy + "]";
}
}
public interface EmpInfoRepository extends JpaRepository<EmpInfo, String> {
}
use this to save list of entities as follows
#Autowired
private EmpInfoRepository empInfoRepository;
empInfoRepository.save(listOfEntity)
Since there is no custom implementation defined, implementation done by SimpleJpaRepository will be used, which will update the entities according to the #Id annotated field
Related
I'm trying to parse strig xml using JaxB API.
Below is my code
XML
http://www.devx.com/supportitems/showSupportItem.php?co=38898&supportitem=listing1
Pojo Classes
#XmlRootElement(name = "employees")
public class FileWrapper {
private LinkedHashSet<Employee> employees;
public LinkedHashSet<Employee> getEmployees() {
return employees;
}
#XmlElement(name = "employee")
public void setEmployees(LinkedHashSet<Employee> employees) {
this.employees = employees;
}
}
Employee.java
import javax.xml.bind.annotation.XmlAttribute;
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlAttribute
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlAttribute
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlAttribute
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlAttribute
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlAttribute
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlAttribute
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlAttribute
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}
MainEntry
public class TestEntryPoint {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(FileWrapper.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("XML from above link as String");
FileWrapper person = (FileWrapper) unmarshaller.unmarshal(reader);
List<Employee> emp = new ArrayList<Employee>(person.getEmployees());
System.out.println(emp.get(0).getFirstname());
}
}
So when am trying to extract any tag's value its showing null. Is there any problem with my XML's data structure or pojo classes ? I'm stuck in this from last couple of hours.
What am doing wrong ? Canyone suggest please ?
Thanks
Annotations in Employee class refer to XML attributes instead of the elements.
Here is corrected version:
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlElement(name = "division")
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlElement(name = "firstname")
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlElement(name = "title")
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlElement(name = "building")
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlElement(name = "room")
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlElement(name = "supervisor")
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlElement(name = "lastname")
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}
Using Hibernate 3.6.0
I'm having a real hard time understanding hibernate. I keep running into this issue with lazy initialization exception.
I have an Event entity with a one-to-many relationship with RSVP. When a run a test get back a list of events it works. But when I'm making the call in my controller in order to return it as json, I run into this lazy init error.
This is my event class
#Entity
#Table(name = "EVENT")
public class Event implements Serializable {
#SequenceGenerator(name="event", sequenceName="EVENT_PK_SEQ")
#GeneratedValue(generator="event",strategy=GenerationType.SEQUENCE)
#Id
#Column(name = "EVENT_ID")
private int id;
#Column(name = "DATE_TIME")
private Date date;
#Column(name = "EVENT_NAME")
private String name;
#Column(name = "EVENT_PARTICIPANT_LIMIT")
private int limit;
#Column(name = "EVENT_VISIBILITY")
private boolean visibilty;
#Column(name = "EVENT_LOCATION")
private String location;
#Column(name = "EVENT_DESCRIPTION")
private String description;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private User author;
private Date create_date;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventType eventType;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventClass eventClass;
#OneToMany(cascade = CascadeType.ALL)
private Set<RSVP> rsvps = new HashSet<RSVP>();
#ManyToMany(mappedBy="event")
private Set<Group> groups = new HashSet<Group>();
public Event(int id, Date date, String name, int limit, boolean visibilty, String location, String description,
User author, Date create_date, EventType eventType, EventClass eventClass) {
super();
this.id = id;
this.date = date;
this.name = name;
this.limit = limit;
this.visibilty = visibilty;
this.location = location;
this.description = description;
this.author = author;
this.create_date = create_date;
this.eventType = eventType;
this.eventClass = eventClass;
}
public Event(){
super();
}
#Override
public String toString() {
return "Event [id=" + id + ", date=" + date + ", name=" + name + ", limit=" + limit + ", visibilty=" + visibilty
+ ", location=" + location + ", description=" + description + ", author=" + author + ", create_date="
+ create_date + ", eventType=" + eventType + ", eventClass=" + eventClass + ", rsvps=" + rsvps
+ ", groups=" + groups + "]";
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public boolean isVisibilty() {
return visibilty;
}
public void setVisibilty(boolean visibilty) {
this.visibilty = visibilty;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public EventType getEventType() {
return eventType;
}
public void setEventType(EventType eventType) {
this.eventType = eventType;
}
public EventClass getEventClass() {
return eventClass;
}
public void setEventClass(EventClass eventClass) {
this.eventClass = eventClass;
}
public Set<RSVP> getRsvps() {
return rsvps;
}
public void setRsvps(Set<RSVP> rsvps) {
this.rsvps = rsvps;
}
public Set<Group> getGroups() {
return groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
}
My RSVP
#Entity
#Table(name="RSVP")
public class RSVP {
#Id
#Column(name="RSVP_ID")
#SequenceGenerator(name="rsvp", sequenceName="RSVP_PK_SEQ")
#GeneratedValue(generator="rsvp",strategy=GenerationType.SEQUENCE)
private int rsvpId;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
#JoinColumn(name="STATUS_ID")
private RSVPStatus status;
#ManyToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="EVENT_ID")
private Event event;
public RSVP(int rsvpId, RSVPStatus status, User user, Event event) {
super();
this.rsvpId = rsvpId;
this.status = status;
this.user = user;
this.event = event;
}
public RSVP() {
}
#Override
public String toString() {
return "RSVP [rsvpId=" + rsvpId + ", status=" + status + ", user=" + user + ", event=" + event + "]";
}
public int getRsvpId() {
return rsvpId;
}
public void setRsvpId(int rsvpId) {
this.rsvpId = rsvpId;
}
public RSVPStatus getStatus() {
return status;
}
public void setStatus(RSVPStatus status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
}
MY controller
public class MyController {
private static SessionFactory sf = HibernateUtils.getSessionFactory();
private DataFacade df = new DataFacade(sf);
#RequestMapping(value="home", method=RequestMethod.GET,
consumes= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<List<Event>> getUserCal(){
DataFacade df = new DataFacade(sf);
List<Event> events= df.getAllEventsByAuthor(1);
for(Event e:events){
System.out.println(e);
}
return new ResponseEntity<List<Event>>(events,HttpStatus.OK);
}
}
Your RSVP collection is fetched lazily. (If you don't specify a fetch type, the default is lazy). You need to change it to eager if you are planning to access it after the Hibernate session is closed:
#OneToMany(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
private Set<RSVP> rsvps = new HashSet<RSVP>();
In my Spring boot application, I have collection of Todos and a collection of Courses. In the view of the application, I return the collection of courses and display whatever course I need. The Todos are stored as 1 list which represents all the current Todos. What I would like to do is return a list of Todos for each course. So when the view is opened, the application would display the the course plus the individual todo list for that course.
Is there a way I can use the existing code to incorporate the new functionality. I have created the front end logic and would like to keep that. My initial idea was to add the the course id to the Todo.java, but that did not work.
Todo.java
#Document(collection="todos")
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=250)
#Indexed(unique=true)
private String title;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s', completed='%s']",
id, title, completed);
}
}
TodoRepository.java
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
public List<Todo> findAll();
public Todo findOne(String id);
public Todo save(Todo todo);
public void delete(Todo todo);
}
Courses
#Document(collection = "courses")
public class Courses {
#Id
private String id;
private String name;
private String lecturer;
private String picture;
private String video;
private String description;
private String enroled;
public Courses(){}
public Courses(String name, String lecturer, String picture, String video, String description,String enroled) {
this.name = name;
this.lecturer = lecturer;
this.picture = picture;
this.video = video;
this.description = description;
this.enroled = enroled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLecturer() {
return lecturer;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnroled() {
return enroled;
}
public void setEnroled(String enroled) {
this.enroled = enroled;
}
#Override
public String toString() {
return "Courses{" +
"id='" + id + "'" +
", name='" + name + "'" +
", lecturer='" + lecturer + "'" +
", description='" + description + "'" +
'}';
}
}
I have done this is the past with mySQL but I need to use Oracle:
This is a very simple register user:
application.properties
#Oracle database setup
spring.datasource.url=jdbc:oracle:thin:#999.999.999.11:1521:d3SID
spring.datasource.username=userName
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
server.port = 4000
UserInformation model
#Entity
public class UserInformation {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "firstName")
#Min(2) #Max(15)
#NotNull
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "userName")
private String userName;
#Column(name = "password")
private String password;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UserInformation)) {
return false;
}
UserInformation that = (UserInformation) o;
return id.equals(that.id);
}
#Override
public int hashCode() {
return id.hashCode();
}
#Override
public String toString() {
return "Applicant{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", userName='" + userName + '\'' + ", password='" +
password + '\'' + '}';
}
}
JPA repo
public interface UserLoginRepo extends JpaRepository<UserInformation, Long> {}
Controller method
#RequestMapping(value = "/register", method = RequestMethod.POST)
public UserInformation registerUser(#RequestBody UserInformation user){
return userService.save(user);
}
When I run SELECT * FROM USERINFORMATION; nothing displays.
From my understanding I should not need to set up JPA config since I am doing it in applications.properties.
Did you check if the UserInformation object is coming from request body? As I know you shouldn't use "#RequestBody", just put "UserInformation user" must be in the parameters.
I have a Spring MVC application that handle Users and Structures that can hosts one or more User.
I'm using Hibernate for the persistence and I'm having some issues with the One-To-Many relation between User and Structure.
This is my User model:
#Entity
#Table(name="USERS")
public class User extends DatabaseEntity {
#Id #GeneratedValue
private Long id = 0L;
#Column
#NotEmpty
private String firstName;
#Column
private String lastName;
#Column
private Date birthDate;
#Column
private String nation;
#Column
private String town;
#Column
private String idNumber;
#Column(unique = true)
private String email;
#Column String resetPasswordToken = "";
#Column
private String password;
#Column
private String avatarUrl;
#Column #Enumerated(EnumType.STRING)
private Role role;
#ManyToOne
#JoinColumn(name = "STRUCTURE_ID")
#Cascade({CascadeType.DETACH})
private Structure structure;
public enum Role {
ADMINISTRATOR,
SPECIALIST,
PATIENT,
DOCTOR,
CARE_GIVER
}
public User() {
birthDate = new Date();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Set<Group> getGroups() {
return null;
}
public void setGroups(Set<Group> groups) {
}
public Set<Group> getCreatedGroups() {
return null;
}
public void setCreatedGroups(Set<Group> createdGroups) {
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<HangoutUser> getHangoutUsers() {
return null;
}
public void setHangoutUsers(Set<HangoutUser> hangoutUsers) {
}
public String getResetPasswordToken() {
return resetPasswordToken;
}
public void setResetPasswordToken(String resetPasswordToken) {
this.resetPasswordToken = resetPasswordToken;
}
public Group getStructure() {
return structure;
}
public void setStructure(Structure structure) {
this.structure = structure;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (!email.equals(user.email)) return false;
if (!id.equals(user.id)) return false;
return true;
}
#Override
public int hashCode() {
Long res = id;
if(id == null)
res = 0L;
int result = res.hashCode();
result = 31 * result + email.hashCode();
return result;
}
}
And this is my Structure model:
#Entity
#Table(name = "STRUCTURES")
public class Structure extends DatabaseEntity {
#Id #GeneratedValue
Long id = 0L;
#Column
String name;
#Column
String address;
#Column
String city;
#Column
String state;
#OneToMany(mappedBy = "structure", fetch = FetchType.EAGER)
#Cascade({CascadeType.DELETE})
Set<User> users = new HashSet<User>();
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public Set<User> getUsers()
{
return this.users;
}
public void setUsers(Set<User> users)
{
this.users = users;
}
}
My issue is that when I try to find all the Users with the value STRUCTURE_ID evaluated, I get an Hibernate Exception, like this:
org.springframework.orm.hibernate3.HibernateSystemException: Found two representations of same collection: it.amtservices.livinglab.model.Group.users; nested exception is org.hibernate.HibernateException: Found two representations of same collection: it.amtservices.livinglab.model.Structure.users
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:690) ...
What should I do to solve this problem? I have already tried many ways but nothing solved.
I paste the abstract repository implementation for the UsersRepository and StructureRepository:
#Transactional
public abstract class AbstractRepository<Model extends DatabaseEntity>
{
Logger logger = Logger.getLogger(this.getClass().getSimpleName());
#PersistenceContext
EntityManager em;
protected Class<Model> ModelClass;
protected List<Model> findBy(String parameterName, Object parameterValue)
{
Query q = em.createQuery("select t from " + ModelClass.getSimpleName() + " t where t." + parameterName + " = :" + parameterName);
q.setParameter(parameterName, parameterValue);
List<Model> results = null;
try
{
results = q.getResultList();
}
catch (Exception e)
{
return null;
}
return results;
}
protected List<Model> findBy(Map<String, Object> parameters)
{
String whereClause = "";
for (String key : parameters.keySet())
{
if (!whereClause.equals("")) whereClause += " and ";
whereClause += "t." + key + " = :" + key;
}
Query q = null;
try
{
q = em.createQuery("select t from " + ModelClass.getSimpleName() + " t where " + whereClause);
}
catch (Exception e)
{
e.printStackTrace();
}
for (String key : parameters.keySet())
{
q.setParameter(key, parameters.get(key));
}
List<Model> results = null;
try
{
results = q.getResultList();
}
catch (Exception e)
{
return null;
}
return results;
}
protected Model findOneBy(String parameterName, Object parameterValue)
{
List<Model> results = findBy(parameterName, parameterValue);
if (results != null && results.size() > 0) return results.get(0);
return null;
}
protected Model findOneBy(Map<String, Object> parameters)
{
List<Model> results = findBy(parameters);
if (results != null && results.size() > 0) return results.get(0);
return null;
}
public Model findOne(Long id)
{
return findOneBy("id", id);
}
public List<Model> findAll()
{
Query q = em.createQuery("select t from " + ModelClass.getSimpleName() + " t");
List<Model> results = null;
try
{
results = q.getResultList();
}
catch (Exception e)
{
return null;
}
return results;
}
public boolean save(Model model)
{
try
{
Model newModel = em.merge(model);
if (model.getId() == 0L) model.setId(newModel.getId());
}
catch (Exception e)
{
logger.error(ModelClass.getSimpleName() + "Repository: " + e.getMessage());
return false;
}
return true;
}
public void save(List<Model> models)
{
for (Model model : models)
{
save(model);
}
}
public void delete(Model model)
{
delete(model.getId());
}
public void delete(Long id)
{
beforeDelete(findOne(id));
try
{
Query q = em.createQuery("delete from " + ModelClass.getSimpleName() + " t where t.id = :id").setParameter("id", id);
q.executeUpdate();
}
catch (Exception e)
{
logger.error(ModelClass.getSimpleName() + "Repository: " + e.getMessage());
}
}
public void delete(Collection<Model> models)
{
for (Model model : models)
{
delete(model.getId());
}
}
public void deleteAll()
{
for (Model model : findAll())
{
delete(model);
}
}
public abstract void beforeDelete(Model model);
public List<Model> find(List<Long> ids)
{
List<Model> models = new ArrayList<Model>();
for (Long id : ids)
{
Model model = findOne(id);
if (model != null) models.add(model);
}
return models;
}
}
Thank you!