Reputation: 597
I have attached a snapshot of my tables data .table name is orderdetail
.
I want to get data on base of customers. Like in my case data should be find on base of PurchasedBy
.
@Entity
public class OrderDetail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name="purchased_By")
private User purchasedBy;
I am trying to use following query in OrderDetailDao
repository
List<OrderDetail> findByPurchasedBy(User user);
but I am getting an error:
Caused by: java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [purchasedBy] on this ManagedType [com.example.Domain.OrderDetail]
Edit Summary >
when i use findAll()
and return json there purchasedBy
section looks like this:
"purchasedBy":{
"id":15,
"email":"[email protected]",
"password":"$2a$10$jj41EbJZTOBfbKdJ6wAdx.rdQq8qU3OqoSzS5mvDVaiL33G1U4pPC",
"name":"admin",
"lastName":"admin",
"active":1,
"roleselected":null,
"roles":[
{
"id":1,
"role":"admin",
"users":[
],
"new":false
}
],
"new":false
}
}
Upvotes: 6
Views: 6305
Reputation: 781
without using custom query jpa repository support this. check following code it working and i tested it.
@Entity
@Table(name = "order_details")
public class OrderDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "purchased_By")
private User purchasedBy;
}
Following is repository class:
public interface OrderDetailsRepository extends JpaRepository<OrderDetails, Integer> {
public List<OrderDetails> findByPurchasedBy(User user);
}
And service class method is like:
@Autowired
public OrderDetailsRepository orderDetailsRepository;
public List<OrderDetails> getUserOrders(Integer userId) {
User user = userRepository.findOne(userId);
return orderDetailsRepository.findByPurchasedBy(user);
}
using following dependency versions:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
There are many new features supported after jpa 1.4 check them.
Upvotes: 2
Reputation: 1397
I think using a custom query might solve the issue:
@Query("select od from OrderDetail od where od.PurchasedBy.id = ?1")
List<OrderDetail> findByPurchasedBy(Integer userId);
Upvotes: 6