I try to use mybatis-generate to generate entity and use rootclass to let the generator entities to extend the BaseEntity.
public class BaseEntity{
private Long id;
getter and setter...
}
But after I run mybatis-generate,the properties in BaseEntity are override in child entities,like:
public class User extend BaseEntity{
private Long Id;
other properties and getters and setters...
}
The Id property should not appear in User classs,because there is an Id property in BaseEntity.
and my configration of rootClass in gengerator-config.xml is :
<javaModelGenerator targetPackage="${mybatis.type-aliases-package}"
targetProject="${target.project}">
<property name="rootClass"
value="site.bigbear.classmate.party.pojo.BaseEntity"/>
</javaModelGenerator>
What's wrong with my code?
Related
I'm currently using Quarkus combined with Blaze Persistence for my microservice. I have the following entity model:
#Entity
public class Content extends BaseEntity {
private boolean deleted;
private boolean published;
}
#Entity
public class WebContent extends Content {
private String webpage;
}
I've mapped the entities to the following EntityViews:
#EntityView(Content.class)
#EntityViewInheritance
#CreatableEntityView
#UpdatableEntityView
public interface ContentUpdateView {
#IdMapping
Long getId();
boolean isPublished();
void setPublished(boolean published);
}
#EntityView(WebContent.class)
#CreatableEntityView
#UpdatableEntityView
public interface WebContentUpdateView extends ContentUpdateView {
String getWebpage();
void setWebpage(String webpage);
}
I have the following method in my ContentsResource:
#POST
public ContentUpdateView save(ContentUpdateView content) {
return contentsService.save(content);
}
When I invoke the post operation I only get the base ContentUpdateView and not the WebContentUpdateView. Is there any configuration to do? (with Jackson I use #JsonTypeInfo and #JsonSubType annotation on the entities to accomplish this).
Thanks
euks
I got it working using Jackson annotation. Here's the base class:
#EntityView(Content.class)
#EntityViewInheritance
#JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = DescriptiveContentView.class, name = "descriptive"),
#JsonSubTypes.Type(value = MediaContentView.class, name = "media"),
#JsonSubTypes.Type(value = WebContentView.class, name = "web")
})
#JsonTypeName("content")
public abstract class ContentView {
#IdMapping
public abstract Long getId();
public abstract boolean isPublished();
}
And here's a subclass:
#EntityView(DescriptiveContent.class)
#JsonTypeName("descriptive")
public abstract class DescriptiveContentView extends ContentView {
public abstract Set<LocalizedParagraphView> getLocalizedParagraphs();
}
I'm using abstract classes for other purposes, but it also works with interfaces.
i'm facing this issue while using Spring JPA and trying to retrieve a List of objects.
This is the class i'm trying to retrieve
#Entity
#Table(name="OBJECTSTERMIC")
public class TermicObject {
#Id
#Column(name="TERMICID")
private long termicId;
#MapsId
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="OBJECTID",columnDefinition="INTEGER")
private Object object;
#Column(name="CONTECA_RIF")
private int contecaRif;
#Column(name="CONTECA_VAL")
private int contecaVal;
#Column(name="TYPE")
private String type;
//getters and setters
The Object class has the primary key on MySQL stored as an Integer, indeed this is Object
#Entity
public class Object {
#Column(name="OBJECTID")
#Id
#JsonProperty("OBJECTID")
private int objectId;
....
So, nowhere is set a Long...
Now, i simply call in a service class
#Override
public List<TermicObject> findAll() {
return repository.findAll();
}
and got this exception
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class it.besmart.db_eipo.persistence.model.Object. Expected: class java.lang.Integer, got class java.lang.Long; nested exception is java.lang.IllegalArgumentException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class it.besmart.db_eipo.persistence.model.Object. Expected: class java.lang.Integer, got class java.lang.Long
Where is set that Object Id should be Long?
Have a look at definition of your repository. Does it have right generic type? do you have Integer as second parameter? IMHO this can be root cause. See proposed correct version:
#RepositoryRestResource
public interface TermicObjectRepository extends JpaRepository<TermicObject, Integer> {
public Optional<TermicObject> findById(Integer id);
public List<TermicObject> findAll()
}
As per #Lubo's answer, in my case I was having compatibility issues between String and Long types and as my model required a Long autogenerated id I had to change the repository from
public interface ProductRepository extends JpaRepository<Product, String> {
}
to
public interface ProductRepository extends JpaRepository<Product, Long> {
}
And my controller from
#RequestMapping(path = "/products/delete/{id}", method = RequestMethod.DELETE)
public void deleteProduct(#PathVariable(name = "id") String id) {
productRepository.deleteById(id);
}
to
#RequestMapping(path = "/products/delete/{id}", method = RequestMethod.DELETE)
public void deleteProduct(#PathVariable(name = "id") Long id) {
productRepository.deleteById(id);
}
You have to define your id as a Long datatype.
#Id
#Column(name="TERMICID")
private Long termicId;
also make a change in your repository interface:
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Got this because
public class MyEntity {
#Id()
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private int id; // <-------- int
...
public long getId() { return id; } // <-------- long
}
Not completely sure, but I think this mapping
#Id
#Column(name="TERMICID")
private long termicId;
#MapsId
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="OBJECTID",columnDefinition="INTEGER")
private Object object;
Makes the id of the Object match the value of termicId which is a long.
use
Long.valueOf(intValue)
to cast int to Long type because you define type Long to #Id
I've been searching for three days, and my error still exist, I've tried a lot of solutions without any positive result !
I've ManyToMany relations, and here is my JPA mapping :
#Entity
public class Facteur implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long idF;
.....
#ManyToMany
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name="Affectation",joinColumns=#JoinColumn(name="IdF"), inverseJoinColumns=#JoinColumn(name="idT"))
private List<Tournee> tournees;
.......
}
"Tournee" Class is like this
#Entity
public class Tournee implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int idT;
....
#ManyToMany(mappedBy="tournees")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Facteur> facteurs;
....
}
here is my controller :
#RequestMapping(value="/getFacteur/", method=RequestMethod.GET)
#ResponseBody
public Facteur getFacteurById(#RequestParam("id") Long idF) {
Facteur f = facteurService.getById(idF);
System.out.println(f.toString());
return f;
}
and JQuery code is :
$(document).ready(function() {
$(".updatelink").click(function() {
var facteurId = $(this).data("facteur-id");
$.ajax({
type : "GET",
url : "http://localhost:8080/distribution/facteur/getFacteur/",
data : { id : facteurId },
success : function(data) {
alert('SUCCESSS');
},
error : function(){
alert("ERROR");
}
});
});
});
Any solutions ?
Best regards !
One of the two sides of the relationship should not be serialized in order to avoid the infinite loop that causes your stackoverflow error. You can use #JsonManagedReference and #JsonBackReference to avoid the error:
//class Facteur
#ManyToMany
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name="Affectation",joinColumns=#JoinColumn(name="IdF"), inverseJoinColumns=#JoinColumn(name="idT"))
#JsonManagedReference
private List<Tournee> tournees;
//class Tournee
#ManyToMany(mappedBy="tournees")
#LazyCollection(LazyCollectionOption.FALSE)
#JsonBackReference
private List<Facteur> facteurs;
Add the #JsonManagedReference in the forward part of the relationship which you want to serialize, and add #JsonBackReference in the back part of the relationship which will not be serialized. In fact, if you serialize a Tournee instance to JSON, you will not get the Facteur array instance. To avoid this drawback, just use the simple #JsonIgnore, but keep in mind, that therefore getters and setters will be ignored during serialization.
You are running into stackoverflow error since Facteur class has reference to tournees and Tournees in turn refers to Facteur - circular refernce while JSON serialization.
Just add #JsonIgnore annotation to private List<Tournee> tournees; declaration in Facteur class and you should be fine.
I used the RestyGWT's JsonEncoderDecoder interface to encode/decode some objects. Among them there are instances of classes having properties not exposed using getter/setter methods. I tried annotating corresponding properties with org.codehaus.jackson.annotate.JsonProperty. But it's not working, causing error
[ERROR] [jsonsample] - field must not be private: com.mycompany.jsonsample.ItemList.items
com.mycompany.jsonsample.ItemList is the class with property items which has no getter/setter and annotated as said above.
Also is it possible to tell the encoder/decoder to skip some properties?
Example with private field and annotated constructor, you should provide more info on your problem though.
public abstract class Parent
{
#JsonCreator
public Parent(#JsonProperty("name") String name)
{
this.name = name;
}
#Override
public String getName()
{
return name;
}
private String name;
}
It is storing an integer in the database not the string as I requested.
Here is the class that contains the enum.
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
public abstract class Document extends BaseModel {
private String title = new String();
private String description = new String();
**#Enumerated(EnumType.STRING)
private DocumentType documentType;**
#Embedded
private DocumentImage documentImage;
// if document should be displayed or published on the web site.
private Boolean published = new Boolean(false);
public Document(DocumentType docType) {
super();
documentType = docType;
setDocumentImage(new DocumentImage());
}
}
and here is the enum class:
public enum DocumentType {
policy,procedure,webbookmark,newsrelease,collectionLetter,whitepaper,busform,
newsarticle ;
}
I know this should work. Any ideas?
One possible reason is that your #Enumerated annotation doesn't take effect because annotations in BaseModel are placed on properties rather than on fields. Placement of annotations on fields or properties should be consistent across inheritance hierarchy.