JPA custom findOne and findAll - jpa

I have a table place that contain as column "state" (it is an Enum that can be 'ACTIVE' or 'INACTIVE')
I would like to know if there is a way with JPA2 that when i call placeRepository.findAll() or placeRepository.getOne(id) only select the row in the database that are marked as "ACTIVE" ?
something like this
List<Place> findByStateActiveOnly();
EDIT:
Bonus question:
I'am at the moment refactoring my project to be able to add a place (and other entities) in a pending state. Because I have added an extra column "state" now i have to add to ALL my queries this condition "AND p.state=my.package.State.ACTIVE" like this;
#Query("select p from Place p where p.idPlace = ?1 AND p.state=my.package.State.ACTIVE")
Isn't there a way to tell jpa to automatically select me if the state is ACTIVE ?
Thank you!

With Hibernate, you can try annotating your entity with #Where, something like this
#Entity
#Where(clause = "state = 'ACTIVE'")
public class Place {...}

Do with parameter:
public interface YourRepository ... {
List<Place> findByState(String state);
}
you will invoke like:
List<Place> placeList = youRepository.findByState("ACTIVE");

Related

C# EF query for typical products - category relationship?

Using entity framework, trying to get some help for a query (prefer method based syntax) for this typical use case:
There is a products table, like:
ownerId
productId
ProductCategoryId
productInfo, etc.
There is a typical product-category-mapping table, like:
somePrimaryKey
ownerId
categoryId
productId
sortOrder
This set up allows one product to be in multiple category, and has its own sort order in each category. Also, we have the "ownerId" in all tables since each owner can only see his own data.
Now, given a categtoryId and ownerId, we need to find all products of this category, sorted by the sortOrder.
Any way how we should write this?
Many Thanks!
You can try to use something along those lines :
// Instanciate your context.
// Do it the way you've already done it, it's here only for example.
DbContext bd = new DbContext();
// The query :
List<Products> listProducts = new List<Products>();
listProducts = db.Products.Where(p => (db.ProductsCategories.Where(pc => pc.CategoryID == categoryID && pc.OwnerID == ownerID).Select(pc => pc.ProductID).OrderBy(pr => pr.sortOrder).ToList()).Contains(p.ProductID)).ToList();
This way use the product-category mapping (categorieID and ownerID are the datas you inject and you keep the sorting.

Is it possble to write query at JPA entity property level

Is it possble to write query at JPA entity property level?
Basically I want to add a property in an entity which is not an actual column and value should computed with query.
Something like:
#Entity
#Table(schema = "quote", name = "QUOTE_SCENARIO")
public class QuoteScenario {
#Query(Select max(Lead_Time) from differentEntity)
private Integer leadTime;
}
No. This is not possible as the query annotation is at the method level. You can try and do this using formula in Hibernate.

Select custom columns from Laravel belongsToMany relation

Im trying to select only specific attributes on the many-to-many relation users, just like in one-to-one. But using select() on belongsToMany() seem to be ignored and i'm still getting all the User attributes.
class Computer extends Eloquent {
public function users() {
return $this->belongsToMany("User")->select("email");
}
public function admin() {
return $this->hasOne("User")->select("email");
}
}
Computer::with("users")->get();
Is there a way of filtering only specified columns from related entity with belongsToMany()?
Yes, you actually can.
Computer::with("users")->get(array('column_name1','column_name2',...));
Be careful though if you have the same column name for both tables linked by your pivot table. In this case, you need to specify the table name in dot notation, tableName.columnName. For example if both users and computer has a column name id, you need to do :
Computer::with("users")->get(array('users.id','column_name2',...));
According to Taylor Otwell it is not currently possible: https://github.com/laravel/laravel/issues/2679
I have tried to use a lists('user.email') at the end of the query but I can't make it work.
Computer::with(["users" => function($query){
$query->select('column1','column2','...');
}])->get();

TypedQuery<x> returns vector of Object[] instead of list of x-type object

I have a method:
public List<Timetable> getTimetableTableForRegion(String id) {
List<Timetable> timetables;
TypedQuery<Timetable> query = em_read.createQuery("SELECT ..stuff.. where R.id = :id", Timetable.class).setParameter("id", Long.parseLong(id));
timetables = query.getResultList();
return timetables;
}
which returns this:
so, what am I missing in order to return a list of Timetable's?
ok, so, ..stuff.. part of my JPQL contained an inner join to other table. Even through in SELECT there were selected fields just from one table, which was used as type - Timetable, Eclipslink was unable to determine if this fields are part of that entity and instead of returning list of defined entity returned list of Object[].
So in conclusion: Use #OneToMany/#ManyToOne mappings (or flat table design) and query just for ONE table in your JPQL to be able to typize returned entities.
Not sure it might be something is looking for, but I had similar problem and converted Vector to ArrayList like this:
final ArrayList<YourClazz> results = new ArrayList<YourClazz>();;
for ( YourClazzkey : (Vector<YourClazz>) query.getResultList() )
{
results.add(key);
}
i have faced the same problem. and my entity has no one to one or one to many relationship. then also jpql was giving me queryresult as vector of objects. i changed my solution to query to criteria builder. and that worked for me.
code snippet is as below:
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Timetable> criteria = builder.createQuery(Timetable.class);
Root<Enumeration> root = criteria.from(Timetable.class);
criteria.where(builder.equal(root.get("id"), id));
List<Timetable> topics = this.entityManager.createQuery(criteria) .getResultList();
return topics;

Entity Framework and Sorting

I'm trying to sort a list of entities using a GridView in ASP.NET, but I can't seem to get it working following examples. I have a property called Name on my entity, and I'm trying to sort by a specified column if given, or the Name column if the sortExpression is empty.
public static List<Product> GetProducts(int startRowIndex, int maximumRows, string sortExpression) {
using(var context = new ShopEntities()) {
var products = context.Products;
products.OrderBy("it."+(string.IsNullOrEmpty(sortExpression) ? "Name" : sortExpression))
.Skip(startRowIndex)
.Take(maximumRows);
return products.ToList();
}
}
I can't get it to sort though. The only other option seems to be doing a switch on the property name for every property in the entity and using a lambda.
OrderBy doesn't mutate the expression. It returns a new expression, which your code ignores. Change your code to:
products = products.OrderBy("it."+ //...