Hibernate QuerySyntaxException, Table not mapped - mysql

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 = ?"

Related

database relation between two different server

I have two servers and both of them contain several tables. Many of them contain relations. Now I need to join those tables and fetch data. I have no clue how to write this sort of query. Currently, I'm working in Laravel. Any suggestions will help me.
Thanks in advance.
If you want to use model relationships you can add connection and table field in your model;
class User extends Model {
public $connection = 'firstconnection';
public $table = 'users';
...
public function comments() {
return $this->hasMany(Comment::class);
}
}
class Comment extends Model {
public $connection = 'secondconnection';
public $table = 'comments';
...
}
You can define connections in your config/database.php, default connection is mysql.
If you write raw queries you can use full table path (specify database):
SELECT * FROM db1.users JOIN db2.comments ON db1.users.id = db2.comments.user_id;
Note: you must have enough privileges on both tables to join and select data. If you use exists, has or semething like that where ORM needs to join two table.
Hope this helps you

Spring boot, execute custom query

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

JPA: How to represent JoinTable and composite key of a JoinTable?

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"

Select query in hibernate annotations in spring mvc

Hi i am writing an spring mvc, employee application using mysql database,hibernate annotations and jsp . The database contains one table "Empdata" where empid is primary key.And there is a column "team" in "Empdata".I want to select employees in a specific team, example all the details of employees in "Team1".Here i can perform delete and edit operations in the application. For delete opertaion i am using
sessionfactory.getCurrentSession().createQuery("DELETE FROM Resource WHERE empid=" +resource.getEmpId()).executeUpdate();
query.I know the commandline query for select is
SELECT * FROM EmpData ERE EMPLTEAM ="Team1"
I want to know how to convert this query into hibernate.
please help,thanks in advance..
you can convert the query in the following way:
String sql = "select ed from EmpData ed where emplTeam = :emplTeam";
Query query = session.createQuery(sql);
query.setParameter("emplTeam ", team);
List<EmpData> empDataList = (List<EmpData>)query.list();
but you should have a class called EmpData containing a property emplTeam similar to the following:
#Entity
#Table(name = "EmpData")
class EmpData {
....
#Column(name = "EMPLTEAM")
private String emplTeam;
public String getEmplTeam() {
return emplTeam;
}
public void setEmplTeam(String emplTeam) {
this.emplTeam = emplTeam;
}
}
(I used annotations hibernate .. but you can do it the same way using .hbm.xml files)
For example
Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Raj");
In your case i guess the Entity name is Empdata(The object that represent the table)
And the field in the object is team(That has getter and setter in object)
Query query = session.createQuery("from Empdata where team=:teamParam");
query.setParameter("teamParam", "team1");

ejb3 toplink jpa 1.0 querying and sequencing

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 :) .