Let's say I have a webapp where users can follow other users.
In my database, I have a User table, and a Following table.
The Following table just has two values: a followingUserId and a followedUserId.
In Java, I have a User class. Most tutorials I see involve one object containing a set of objects it's related to. So many tutorials can describe how to have Users have a set of users following that user, and a set of users followed by a user. But that would require a lot of memory.
I'm thinking of an alternate structure where a User object has no info about following. Instead, there is a Following object that looks like this
#Entity
#Table(name = "Following")
public class Following {
RegisteredUser follower;
RegisteredUser followed;
}
and corresponds to the join table. When I want to get all the followers of a user, I can do a query for all Following objects with that user as the follower.
My issues are:
The Followers Table has a composite key of each of the two userids. How can I use annotations to represent that composite key? The #Id annotation denotes a single variable as the key
How can I do such a query?
If it's relevant, I am using MySQL as the db
If using JPA > 2.0, you can mark relationships as your ID:
#Entity
#Table(name = "Following")
#IdClass(FollowingId.class)
public class Following {
#Id
RegisteredUser follower;
#Id
RegisteredUser followed;
}
public class FollowingId implements Serializable {
private int follower;
private int followed;
}
the types within the followingId class must match the type of the RegisteredUser Id. There are plenty of more complex examples if you search on JPA derived ID.
For queries, it depends on what you are looking for. A collection of followers for a particular user could be obtained using JPQL:
"Select f.follower from Following f where f.followed = :user"
Related
Im newbie to web development,and I did some examples like get data from mysql db and show them in a jsp pages.(use CRUDRepository )
but in that way we can only show only one table data.
what should we do if we want to show combine two table data.
I found these while um searching,simply I m asking how we put a more complicated sql query to this.
public interface UserRepository extends JpaRepository<User, Long> {
#Query("select u from User u where u.lastname like ?1%")
List<User> findByAndSort(String lastname, Sort sort);
#Query("select u.id, LENGTH(u.firstname) as fn_len from User u where u.lastname like ?1%")
List<Object[]> findByAsArrayAndSort(String lastname, Sort sort);
}
if we can put that complicated query (like three tables or more) here,
should we create a new entity class according to query coloumns ??
then again is that work because actually there isn't any table like that.
To get more complex data from DB you can use projections, for example:
public interface UserProjection {
Long getId();
Long getFirstNameLen();
}
#Query("select u.id as id, LENGTH(u.firstName) as firstNameLen from User u where u.lastname like ?1%")
List<UserProjection> getProjections(String lastName, Sort sort);
Note that you should use aliases in the query that must match with getters in the projection (... as firstNameLen -> getFirstNameLen())
The same way you can get data from several (joined) entities.
If you have an entity with some associations, for example:
#Entity
public class User {
//...
#OneToMany
private List<Role> roles;
}
then you can use repository method to get the users and their roles data even without any projection, just for the main entity (User). Then Spring does the rest of the work itself:
#EntityGraph(attributePaths = "roles")
List<User> findByFirstNameContainingIgnoreCase(String firstName);
or the same with query:
#Query("select distinct u from User u left join fetch u.roles where upper(p.firstName) like concat('%', upper(?1), '%')")
List<User> findWithQuery(String firstName);
In this case all users will have their lists of roles are filled with data from the roles table.
(Note to use distinct in the query to prevent the result from duplicated records, more info see here.)
Useful resources:
Spring Data JPA - Reference Documentation
Query Creation
Repository query keywords
Projections
SpEL support in Spring Data JPA #Query definitions
Hibernate ORM User Guide
Associations
HQL and JPQL
JPQL Language Reference
I'm following this Tutorial. I have added another DAO where i'm retrieving the admin_roles table. The method looks like this
public List findAllAdminRoleByUserName(String userName) {
List<AdminRoles> users = new ArrayList<AdminRoles>();
Query hqlQuery = sessionFactory.getCurrentSession().createQuery("from admin_roles AdminRoles where AdminRoles.username = ?");
users = hqlQuery.setString(0, userName).list();
if (users.size() > 0) {
return users;
} else {
return null;
}
}
When I try to retrieve i'm getting the following error
HTTP Status 500 - Request processing failed; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: admin_roles is not mapped [from admin_roles AdminRoles where AdminRoles.username = ?]
I am able to get values from the admin table mentioned in this tutorial, also I created some other tables from which i'm able to get values. But only this table is not being mapped. I also tried by changing the name of the table from "admin_roles" to adminroles(in the database and in code) I still get the same error.
The relevant class looks like this. Also the entity annotation is javax
#Entity
#Table(name = "admin_roles", uniqueConstraints = #UniqueConstraint(columnNames = { "role", "username" }))
public class AdminRoles{
Am I missing something? Thanks in advance
You're confusing tables and entities. Tables are a relational database concept. They're mapped to entities, which are Java classes. HQL uses entities. Always. Never tables.
BTW, the message is not "Table not mapped". It's "admin_roles is not mapped". And that's very different. HQL uses entities, so it expects admin_roles in your query to be a mapped entity. Not a table name. And you don't have any entity named admin_roles.
The query should be
select ar from AdminRoles ar where ar.username = ?
That assumes there is a mapped field/property named username in the AdminRoles entity class, of course.
You need to use the entity name in you query. Try like this:
"from AdminRoles AR where AR.username = ?"
I've got 2 models User and Exercise. Now any User can have any Exercise. It's a ManyToMany situation. I modeled it with #ManyToMany, but you can't have a duplicate entry in a ManyToMany. A User is likely to do multiple sets of one exercise so I duplicate entries are required. To get round this I created the join table separately called UserExerciseJoin. User and Exercise had ManyToOne relationships with the UserExerciseJoin model. Though this solved the multiple keys issue I now can't delete from the new table. I get an OptimisticLockException from some of the models associated to the Exercise.
My question is: Am I on the right path with the seperate table or is there something I can do to a standard #ManyToMany to make it accept duplicate entries?
If I understand it right in your model, then yes, it is probably not the case for #ManyToMany. It seems to me that you can be better off with a meaningful entity like UserExerciseOccurrence that reference both a User and an Exercise and means a concrete exercise session.
You can also benefit from this approach if you need to save more info about a particular exercise session (like duration, etc).
#Entity
class UserExerciseOccurrence {
#ManyToOne
User user;
#ManyToOne
Exercise exercise;
}
#Entity
class User {
#OneToMany(mappedBy="user", cascade=DELETE)
Set<UserExerciseOccurrence> exerciseOccurrences;
}
#Entity
class Exercise {
#OneToMany(mappedBy="exercise", cascade=DELETE)
Set<UserExerciseOccurrence> exerciseOccurrences;
}
You are on the right path. You should have #OneToMany relation from User class and from Excercise class to this new entity. And in UserExerciseJoin you should have #ManyToOne relations.
So this code should look like this:
#Entity
User {
#OneToMany(mappedBy="user")
private List<UserExercise> userExercises;
....
}
#Entity
Excercise {
#OneToMany(mappedBy="excercise")
private List<UserExercise> userExercises;
....
}
#Entity
UserExercise
{
#ManyToOne
private User user;
#ManyToOne
private Excercise excercise;
...
}
You had an error when deleting this new entity. You had in on some entity related to excercise. It seems that this is because of cascades. You probably set cascades on fields of UserExerciseJoin class. If it was CascadeType.DELETE or CascadeType.ALL cascade then it caused deletion of related entities. So you shouldn't set cascades in UserExercise class. Then deleting of such entity will not cause a problem.
I have 2 questions:
suppose we have one entity named class and another called student. each class has onetomany students.
public class Clas implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;
#OneToMany(cascade=CascadeType.ALL)
Collection<Student> students;
public clas(){
super();
}
..... getters and setters
}
q1: i get the exception there are no fields to be mapped, when adding any other column like String name, it works, but i don't need that field what can i do ?
q2: the ids is autogenerated, and i want to query all students in class c1, but i don't has the id of this class, how to do such query ?
iam working with mysql server glassfish v2.1 toplink jpa 1.0
Thanks
The student class must have a property named 'classID' (or whatever) that refers to the
Clas's id property. That should be annotated like #ManyToOne.
If that's done already by IDE, then check id generation strategy. For example, if you are using mysql, the primary key is auto_increment, then set th id's strategy to
GenerationType.AUTO and recompile. Tell me if any other errors shows up. :) .
ok. I think I understood you question. You may use NamedQueries written in Query Languages dependent on your library (in your case toplink) like EJB QL or HBQL. You can create Session Beans for querying.
public class ClassSessionBean {
#PersistenceContext(unitName="your PU name in persistence . xml")
private Entitymanager em;
publicClas selectByID(int id) throws NoResultException {
Query q = em.createQuery("select class from Class class where class.id=?");
q.setParameter(1, id);
Clas clas = q.getResultList();
return clas;
}
}
Note that the above code may contain syntax errors because I have not checked it anywhere.
Hope you find some help from this :) .
i have been researching on this topic and havent found any answers yet. Im using spring roo and i would like to know if theres a way I can establish a many-to-many relationship with attributes within this relationship. For example i have two tables Employee and MedicalEquipment, Employees can reserve many equipments, and equipment could be reserved by many employee, however i want to store the date this reserve took place.
If some one can help i would appreciate it. Thanks in advance!
In order to achieve a many-to-many relationship with attributes, you need a join table which contains the additional columns. That is, besides Employee and MedicalEquipment, you will need a third EmployeeMedicalEquipment.
Regarding JPA you have two options:
Mapping the join table to an intermediate entity
Mapping the join table to a collection of components
The former is more complicated, but it allowed you to have bidirectional navigation (because it's an entity and hence, can have shared references), the latter is simpler in both building it and using it, but you can't use it to navigate between entities (however, you can write a query to retrieve the objects you need)
Roo is a code generator, but it lacks of all the options that JPA offers, so you have to edit the Java classes, and the test classes. The building of the view has some limitations too, so you will need to edit it as well.
In my case, I needed to create an intermediary entity because the table belongs to a legacy database that already existed.
I did something like this:
entity --class ~.domain.Employee --table T_Employee [etc...]
field [etc...]
entity --class ~.domain.MedicalEquipment --table T_MedicalEquipment [etc...]
field [etc...]
entity --class ~.domain.EmployeeMedicalEquipment --table T_Employee_MedicalEquipment --identifierType ~.domain.EmployeeMedicalEquipmentId
//to store the date this reserve took place.
field date --fieldName reserveDate --column C_reserveDate [etc...]
//Bidirectional: you´ll need #JoinColumn insertable = false and updatable = false
field reference --fieldName employee --type ~.domain.Employee --cardinality MANY_TO_ONE
//Bidirectional: you'll need #JoinColumn insertable = false and updatable = false
field reference --fieldName medicalEquipment --type ~.MedicalEquipment --cardinality MANY_TO_ONE
//Join table's composite primary key
field string --fieldName employeeId --column employee_ID --class ~.domain.EmployeeMedicalEquipmentId [etc...]
field string --fieldName medicalEquipmentId --column medicalEquipment_ID --class ~.domain.EmployeeMedicalEquipmentId [etc...]
//Now, it's time to complete the relationship:
focus --class ~.domain.Employee
field set --type ~.domain.EmployeeMedicalEquipment --fieldName medicalEquipments --cardinality ONE_TO_MANY --mappedBy employee
focus --class ~.domain.MedicalEquipment
field set --type ~.domain.EmployeeMedicalEquipment --fieldName employees --cardinality ONE_TO_MANY --mappedBy medicalEquipment
Furthermore, you need to guarantees referential integrity by managing collections on either side of the association using the constructor. So you need to edit the class in such way:
#RooEntity(...
public class EmployeeMedicalEquipment {
#ManyToOne
#JoinColumn(name = "employeeId", referencedColumnName = "employeeId", insertable = false, updatable = false)
private Employee employee;
#ManyToOne
#JoinColumn(name="medicalEquipmentId", referencedColumnName="medicalEquipmentId", insertable=false, updatable=false)
private MedicalEquipment medicalEquipment;
/**
* No-arg constructor for JavaBean tools
*/
public EmployeeMedicalEquipment() {
}
/**
* Full constructor, the Employee and MedicalEquipment instances have to have an identifier value, they have to be in detached or persistent state.
* This constructor takes care of the bidirectional relationship by adding the new instance to the collections on either side of the
* many-to-many association (added to the collections)
*/
public EmployeeMedicalEquipment(Employee employee, MedicalEquipment medicalEquipment, Date reserveDate) {
this.setReserveDate (reserveDate);
this.employee = employee;
this.medicalEquipment = medicalEquipment;
this.setId(new EmployeeMedicalEquipmentId(employee.getId(), medicalEquipment.getId());
// If Employee or MedicalEquipment Guarantee referential integrity
employee.getMedicalEquipments().add(this);
medicalEquipment.getEmployees().add(this);
}
...
}
I tried to give you an example of a Roo configuration.
You can find a better explanation of the JPA stuff in the book from Manning "Java Persistence with Hibernate", chapter 7.2.3.
Note: if you use roo 1.2.1, the count query will generate SQL with "count(id1, id2)", which is not supported by all databases, including HSQLDB. You can customize it like this:
...
-#RooJpaActiveRecord(identifierType = EmployeeMedicalEquipmentId.class, table = "T_Employee_MedicalEquipment")
+#RooJpaActiveRecord(identifierType = EmployeeMedicalEquipmentId.class, table = "T_Employee_MedicalEquipment", countMethod="")
...
public class EmployeeMedicalEquipment {
...
// count method initially copied from ActiveRecord aspect
public static long countEmployeeMedicalEquipments() {
- return entityManager().createQuery("SELECT COUNT(o) FROM EmployeeMedicalEquipment o", Long.class).getSingleResult();
+ return entityManager().createQuery("SELECT COUNT(o.employee) FROM EmployeeMedicalEquipment o", Long.class).getSingleResult();
}
}
Why can't you have a separate entity to denote your relationship?
Just introduce a new entity called a MedicalEquipmentReservation which would contain all the attributes of the reservation along with the relationships between the Employee and the Medical Equipment entities.
See the following example.
class MedicalEquipmentReservation{
//attributes
Date reservationStartDate;
Date reservationEndDate;
//relationships
Employee employee;
Set<Equipment> equipments; //assuming more than one equipment can be borrowed at one reservation
}
Cheers and all the best with Spring Roo!