I need to search in an h2 database for Company class instances that have a specific code, but I can't figure out how.
I have tried using the Finder class, but there don't seem to be any find methods in the version i am using except findbyid().
Here is the beginning of my Company class:
#Entity
public class Company extends Model {
#Id
public Integer id;
public String code;
public String name;
public String adress;
public String fiscalCode;
public String bankAccount;
public static Finder<Integer, Company> find = new Finder<>(Company.class);
Thank you!
Depending on the version of Play you are using I'd suggest to try the following:
Company.find.where().like("code", "%foo%").findList();
or
Define your finder
public class CompanyFinder extends Finder<Long,Company> {
public CompanyFinder() {
super(Company.class);
}
// Add finder methods ...
public Company byCode(String code) {
return query().eq("code", code).findOne();
}
}
Update your entity to reference this finder:
#Entity
public class Company extends BaseModel {
public static final CompanyFinder find = new CompanyFinder();
...
}
Call the finder:
Company c = Company.find.byCode("foo");
Related
According to this post ResourceAssembler is changed to RepresentationModelAssembler
I have this code which is using Spring HATEOAS 1.0:
import org.springframework.hateoas.ResourceAssembler;
public class BaseAssembler<T extends BaseTransaction, D extends BaseResource>
implements ResourceAssembler<T, D> {
...
}
After migration to implementation 'org.springframework.boot:spring-boot-starter-hateoas:2.6.4'
I changed it to:
public class BaseAssembler<T extends BaseTransaction, D extends BaseResource>
implements RepresentationModelAssembler<T, D> {
.........
}
But I get error:
Type parameter 'D' is not within its bound; should extend 'org.springframework.hateoas.RepresentationModel<?>'
Do you know how I can fix this issue?
The compiler is reporting that the type parameter D is not within its bound in your definition:
public class BaseAssembler<T extends BaseTransaction, D extends BaseResource>
implements RepresentationModelAssembler<T, D> {
.........
}
In other words, it means that you cannot use D extends BaseResource to implement RepresentationModelAssembler<T, D> (note the type parameter D here) because that type should extend 'org.springframework.hateoas.RepresentationModel<?>'.
RepresentationModelAssembler gives you the ability to convert between domain types, your entities, to RepresentationModels, a based class conceived to enrich your DTOs to collect links.
It is defined as follows:
public interface RepresentationModelAssembler<T, D extends RepresentationModel<?>>
Note again the definition of the type parameter D.
In your code you need to use something like:
public class BaseAssembler<T extends BaseTransaction, D extends RepresentationModel<?>>
implements RepresentationModelAssembler<T, D> {
.........
}
Please, consider read for instance some this or this other article, they provide a great variety of examples and uses cases about showcasing how you can implement the desired behavior.
For example, given the following entity, extracted from one of the cited articles:
#Entity
public class Director {
#Id
#GeneratedValue
#Getter
private Long id;
#Getter
private String firstname;
#Getter
private String lastname;
#Getter
private int year;
#OneToMany(mappedBy = "director")
private Set<Movie> movies;
}
And the following DTO:
#Builder
#Getter
#EqualsAndHashCode(callSuper = false)
#Relation(itemRelation = "director", collectionRelation = "directors")
public class DirectorRepresentation extends RepresentationModel<DirectorRepresentation> {
private final String id;
private final String firstname;
private final String lastname;
private final int year;
}
Your RepresentationModelAssembler will look like:
#Component
public class DirectorRepresentationAssembler implements RepresentationModelAssembler<Director, DirectorRepresentation> {
#Override
public DirectorRepresentation toModel(Director entity) {
DirectorRepresentation directorRepresentation = DirectorRepresentation.builder()
.id(entity.getId())
.firstname(entity.getFirstname())
.lastname(entity.getLastname())
.year(entity.getYear())
.build();
directorRepresentation.add(linkTo(methodOn(DirectorController.class).getDirectorById(directorRepresentation.getId())).withSelfRel());
directorRepresentation.add(linkTo(methodOn(DirectorController.class).getDirectorMovies(directorRepresentation.getId())).withRel("directorMovies"));
return directorRepresentation;
}
#Override
public CollectionModel<DirectorRepresentation> toCollectionModel(Iterable<? extends Director> entities) {
CollectionModel<DirectorRepresentation> directorRepresentations = RepresentationModelAssembler.super.toCollectionModel(entities);
directorRepresentations.add(linkTo(methodOn(DirectorController.class).getAllDirectors()).withSelfRel());
return directorRepresentations;
}
}
In terms of your interfaces and object model:
#Entity
public class Director extends BaseTransaction{
#Id
#GeneratedValue
#Getter
private Long id;
#Getter
private String firstname;
#Getter
private String lastname;
#Getter
private int year;
#OneToMany(mappedBy = "director")
private Set<Movie> movies;
}
public class DirectorRepresentationAssembler
extends BaseAssembler<Director, DirectorRepresentation>
implements RepresentationModelAssembler<Director, DirectorRepresentation> {
//... the above code
}
DirectorRepresentation is the same as presented above.
The Spring HATEOAS reference guide itself provides some guidance as well about the changes performed in Spring HATEOAS 1.0 and about how to migrate from the previous version. It even includes a script that may be of help.
In any case, as indicated above, in your use case you only need to modify the BaseAssembler interface to be defined in terms of the type D extends RepresentationModel<?>; then try relating in some way BaseResource to RepresentationModel or get rid of BaseResources and use RepresentationModels instead.
For example, you couild try defining BaseResource as follows:
public class BaseResource extends RepresentationModel<BaseResource>{
// your implementation
}
Then, the bound will be right:
public class BaseAssembler<T extends BaseTransaction, D extends BaseResource>
implements RepresentationModelAssembler<T, D> {
// your implementation
}
With these changes, DirectorRepresentation will extend BaseResource:
public class DirectorRepresentation extends BaseResource {
}
And you can extend BaseAssembler like this:
public class DirectorRepresentationAssembler
extends BaseAssembler<Director, DirectorRepresentation>
implements RepresentationModelAssembler<Director, DirectorRepresentation> {
// your implementation
}
In my opinion, the code you published in your repository is mostly fine. I think the only problem is in this line of code, as I mentioned before, I think you need to provide the type parameter when defining your BaseResource class. For instance:
package com.hateos.test.entity.web.rest.resource;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import org.joda.time.DateTime;
import org.springframework.hateoas.RepresentationModel;
import java.util.UUID;
public class BaseResource extends RepresentationModel<BaseResource> {
#JsonProperty
#ApiModelProperty(position = 1, required = true)
public UUID id;
#JsonProperty
public DateTime creationTime;
#JsonProperty
public DateTime lastUpdatedTime;
}
Please, note the inclusion of the code fragment RepresentationModel<BaseResource> after the extends keyword.
I am not sure if it will work but at least with this change every compiles fine and it seems to work properly.
I'm using Room for my android app. I'm now trying to setup my database, but there is an error message, which says, that the Dao class must be annotated with #Dao. But as you can see in the coding snippet, the Dao class is annotated with #Dao. Does anyone know where the problem or my mistake could be? Both files aren't in the same folder (DAO is in the service folder while the other class is in the model folder)
Device.java
#Entity(tableName = "device")
public class Device {
#PrimaryKey(autoGenerate = true)
public int device_id;
#ColumnInfo(name = "identifier")
public String identifier;
#ColumnInfo(name = "language")
public int language;
#ColumnInfo(name = "searchFilter")
public int searchFilter;
public Device(String identifier, int language, int searchFilter){
this.identifier = identifier;
this.language = language;
this.searchFilter = searchFilter;
}
}
DeviceDAO.java
#Dao
public interface DeviceDAO {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void addDevicePreferences(DifficultType difficultType);
#Query("SELECT * FROM device")
List<Device> selectAllDevicePreferences();
#Update(onConflict = OnConflictStrategy.REPLACE)
void updateDevicePreferences(Device device);
}
Check your database class. When you define DAO, you must have use wrong type(Device instead of DeviceDAO).
Incorrect
public abstract Device deviceDao();
Correct
public abstract DeviceDAO deviceDao();
Hope this will work. Thanks
Error Message:
Dao class must be annotated with #Dao
To solve error please read it properly.
If this error messages shows on Model class then you need to modify your AppDatabase class. I am giving you the code what gives error then error corrected code.
Error Code:
MyImage.java
#Entity
public class MyImage {
#PrimaryKey(autoGenerate = true)
private int uid;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "photo")
private String photo;
public MyImage(String title, String photo) {
this.title = title;
this.photo = photo;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
MyImageDao.java
#Dao
public interface MyImageDao {
#Query("SELECT * FROM myimage")
List<MyImage> getAll();
#Insert
void insertAll(MyImage... myImages);
#Delete
void delete(MyImage myImage);
}
AppDatabase.java
#Database(entities = {MyImage.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract MyImage myImageDao();
}
Here has error on only AppDatabase.java file, you can see myImageDao has return type MyImage, that means it assumed that MyImage is a Dao class but MyImage is model class and MyImageDao is Dao class.
So it need to modify AppDatabase.java class and MyImage to MyImageDao.
The corrected code is-
AppDatabase.java
#Database(entities = {MyImage.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract MyImageDao myImageDao();
}
For Kotlin users :
Check if you've added following line in your Database file.
abstract val myDatabaseDao:MyDatabaseDao
I was facing the same issue, after struggling for some time I realized that in the database class, I created a variable of Entity class instead of Dao class.
Check if you have any additional methods in your interface. In my Kotlin implementation I had:
#Dao interface DeviceDao {
#get:Query("SELECT * FROM extdevice")
val all: List<ExtDevice>
fun first() : ExtDevice? {
val devices = all
if (devices.isNotEmpty())
return devices[0]
return null
}
}
removing first() solved my issue:
#Dao interface DeviceDao {
#get:Query("SELECT * FROM extdevice")
val all: List<ExtDevice>
}
add
import androidx.room.Dao;
to your interface that u set querys on it and then add the first line from this code
#Dao
public interface UserDeo {
#Query("SELECT * FROM user")
List<User> getAllUsers();
#Insert
void insertAll(User... users);
}
Your syntax look correct by what i can tell. Have you tried the following things:
Are your imports complete?
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
Mabe delete them an reimport all.
Have you rebuild / Gradel Build the project?
I did a Project with Room as well and i had no problems having the same syntax.
in my case, i have implement #Dao annotation and still get the error. the error is :
error: Dao class must be annotated with #Dao public final class NonExistentClass{ }
just make sure your room dependencies version same as the others, my room dependencies :
kapt "androidx.room:room-compiler:2.2.0"
implementation "androidx.room:room-runtime:2.2.0"
implementation "androidx.room:room-ktx:2.2.0"
don't forget to use kapt instead of annotation processor and add :
apply plugin: 'kotlin-kapt'
above your build.gradle module app, because annotationProcessor will cause another errors, like database_impl.
then you should clean and build the project
hope it will help whoever see this
#Database(entities = {ObjInspectionSqlite.class}, version = 2, exportSchema = false)
#TypeConverters({InspeccionDateTypeConverter.class})
public abstract class DataBaseInspections extends RoomDatabase {
public static BaseDeDatosInspecciones instance;
public abstract InspectionsDao inspectionsDao();
public abstract ObjInspectionSqlite inspectionSqlite();
...
}
note that ObjInspectionSqlite is a class whit #Entity , and I've declared it abstract in my DataBase
This will trow:
"error: Dao class must be annotated with #Dao"
even if you declared your dao correctly.
Maybe you declared your class as an abstract somewhere in your database and the DB expects it to be an abstract Dao that can be implemented.
Add code snippet of your DataBase since all answers point to a coding error in that class.
Is there any way to create this type of structure in Java?
In Python it is possible, but we're programming the App Engine in Java and we don't have any idea how to make this.
Just use a List:
#Cache
#Entity
class MyClass implements IsSerializable{
public List<Log> logs;
...
In your Log class define your 4 fields:
#Entity
public class Log implements IsSerializable {
public String property1;
public String property2;
public String property3;
public String property4;
....
}
I assume you are using Objectify
I'm trying to use inheritance with ORMLite and I can't work out if it is supported or not from looking at the documentation and googling.
What I want to do is have
public abstract class Person{
public int id;
public String name;
}
public class Student extends Person{
public String school;
public String year;
// other student stuff
}
public class Teacher extends Person{
public String title;
// other teacher stuff
}
What I can't work out (assuming it's supported) is how to annotate the 3 classes for ORMLite.
Do I only need to annotate the concrete classes with #DatabaseTable(tableName = "Student") or do I need the abstract class also?
I keep getting errors like:
04-24 10:18:30.857: E/AndroidRuntime(30495): Caused by: java.lang.RuntimeException: java.sql.SQLException: Unknown field 'name' from the Android sqlite cursor, not in:[year, school]
The #DatabaseTable annotation is only necessary on the Student or Teacher tables and would not be used if it was on the Person base class.
What you need to have is a #DatabaseField annotation on the id and name fields in Person. For example:
public abstract class Person{
#DatabaseField(generatedId = true)
public int id;
#DatabaseField
public String name;
}
ORMLite should walk the class hierarchy and any fields from the base class should be included in the Student and Teacher tables. If you edit your question to show the #DatabaseField or other annotations, I can comment more.
Ok for that but now, how to implements, in that example, a fourth class containing a List<AbstractPerson> ?
I precise my question :
public class ClassRoom {
#ForeignCollectionField(foreignFieldName="asYouWant")
public Collection<Person> peoples;
}
peoples.add(new Student());
peoples.add(new Teacher());
peoples.add(new Student());
because when ormlite will try to access peoples like :
for (Person person : classRoom.peoples)
{
if (person.getType() == Student)
//do stuff
else if (person.getType() == Student)
//do other stuff
}
It won't be able to get personDAO because it doesn't exist (abstract)...
I get all my database functionnal with good Id's and relation, it's just a data access question ?
I'm trying to create a PK class for a JDO Entity named Item. It's was soo simple with JPA, but now im practicing JDO. I'm using anotation configuration and this is how the two classes look like:
#PersistenceCapable(table="ITEM",identityType = IdentityType.APPLICATION,
objectIdClass = ItemPK.class,schema="mgr")
public class Item {
#PrimaryKey
#Persistent(column="code")
private long code; //WHY public?
#PrimaryKey
#Persistent(column="producer")
private String producer;
#PrimaryKey
#Embedded
private ItemPK id;
#Persistent(column="price")
private double price;
#Persistent(column="name")
private String name;
#Persistent(column="description")
private String description;
[... getters/setters...]
}
I want the ItemPK class to be used as a Primary Key class with thoose two columns (code,producer). So this is how the class looks like:
#EmbeddedOnly
#PersistenceCapable(embeddedOnly="true",identityType=IdentityType.APPLICATION)
public class ItemPK implements Serializable{
#Persistent
#PrimaryKey
public long code;
#Persistent
#PrimaryKey
public String producer;
#Override
public String toString() {
return code+"_"+producer;
}
#Override
public int hashCode() {
[...Eclipse autogenerated...]
}
#Override
public boolean equals(Object obj) {
[...Eclipse autogenerated...]
}
}
What I do get after trying to run the code:
[...Caused by]
Nested Throwables StackTrace:
Class pl.edu.pw.mini.entity.jdo.Item has been specified with an object-id class pl.edu.pw.mini.entity.jdo.ItemPK which has a field jdoStateManager which isnt Serializable. All non static fields of an objectId class must be serializable.
org.datanucleus.metadata.InvalidPrimaryKeyException: Class pl.edu.pw.mini.entity.jdo.Item has been specified with an object-id class pl.edu.pw.mini.entity.jdo.ItemPK which has a field jdoStateManager which isnt Serializable. All non static fields of an objectId class must be serializable.
As I understand the enhancer adds jdoStateManager to a ItemPK, ad it is not Serializable. But as ItemPK is embedded, either it should not get the jdoStateManager, or JDO should know the difference between jdoStateManager and a regular field. What am I doing wrong to get an embedded class for a 2-column Primary Key
I have no Idea how to make this thing work, can anyone help me, and tell me what am I doing wrong here?
The docs define perfectly well how to do that
http://www.datanucleus.org/products/accessplatform_3_1/jdo/orm/compound_identity.html
and it doesn't involve use of #Embedded