public class LocationBasedRole extends AbstractEntity{
#ManyToMany(fetch=FetchType.LAZY)
private Set<Role> roles=new HashSet<Role>();
#ManyToMany(fetch=FetchType.LAZY)
private Set<Location> locations=new HashSet<Location>();
}
public class Role extends AbstractEntity{
private String name;
}
public class Location extends AbstractEntity{
private String location;
}
I have an entity named locationBasedRole which has 2 properties named roles and locations. Both roles and locations have a #ManyToMany relation with locationBasedRole.
Now I want to have one property of each in a Vaadin Table. It should be something like this,
public class UserForm extends OgsAbstractForm<User>{
MTable<LocationBasedRole> locationBasedRoleTable = new MTable<LocationBasedRole>().withHeight("100%").withWidth("100%");
#Override
protected Component createContent() {
Set<LocationBasedRole> lbRoles=new HashSet<LocationBasedRole>();
roles.addAll(locationBasedRoleFasade.findAll());
BeanItemContainer<LocationBasedRole> bean=new BeanItemContainer<LocationBasedRole>(LocationBasedRole.class);
//It returns an error on the next both lines and I know the reason, but don't know how to solve it.
// If it was no ManyToMany relation and the properties weren't a collection, it would work
bean.addNestedContainerProperty("roles.name");
bean.addNestedContainerProperty("locations.location");
bean.removeContainerProperty("persistent");
bean.removeContainerProperty("id");
bean.addAll(lbRoles);
locationBasedRoleTable.setContainerDataSource(bean);
return new VerticalLayout(locationBasedRoleTable);
}
}
When I remove the properties from the NestedContainerProperties it shows me at least something in the table.
bean.addNestedContainerProperty("roles");
bean.addNestedContainerProperty("locations");
I could use any help!
Thanks in advance!
So if I understand your question right, you want to have the Collections of your BeanItemContainer-Entity displayed in one column each?
I see two possibilities for that.
Option 1 - use a wrapper class for your Sets and use addNestedContainerBean
One possibility would be to not use Sets inside your LocationBasedRole but to use a wrapper class that extends HashSet.
Then you could use the addNestedContainerBean method.
I created a small example with the BeanItemContainer-Entity Team
public class Team {
private String teamName;
private Members teamMembers;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public Members getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(Members teamMembers) {
this.teamMembers = teamMembers;
}
}
Which consists of a name and teamMembers. The latter is of type Members:
public class Members extends HashSet<TeamMember> {
public String getMembers() {
return this.stream()
.map(member -> member.getFirstName() + " " + member.getLastName())
.collect(Collectors.joining(","));
}
}
Which is a simple wrapper for the Set that contains instances of TeamMember:
public class TeamMember {
private String firstName;
private String lastName;
private Integer age;
// getters and setters
}
As you can see in the Members class, there is a method getMembers which returns a String, containing a comma separated list of the team members names.
If we now use addNestedContainerBean("teamMembers") Vaadin tries to display all properties contained in the class Members. Vaadin will think getMembers is a getter for a String property called members and so generate a column for it.
Vaadin will also display a column "empty" because it will find the isEmpty method of Set and think empty is a property to display in a column. So we tell Vaadin to remove that column.
The final code of my example looks like:
protected Component createContent() {
Set<Team> teams=new HashSet<>();
for (int teamCounter = 0; teamCounter < 5; teamCounter++) {
Team team = createTeam();
addMembersToTeam(5, team);
teams.add(team);
}
BeanItemContainer<Team> bean=new BeanItemContainer<>(Team.class);
bean.addNestedContainerBean("teamMembers");
bean.removeContainerProperty("teamMembers.empty");
bean.addAll(teams);
teamTable.setContainerDataSource(bean);
return new VerticalLayout(teamTable);
}
The result looks like:
Option 2 - create fake getters and use addNestedContainerProperty
The only thing you have to do for this is extend your BeanItemContainer-Entity (LocationBasedRole) and create a fake getter for each Set you want to be displayed in a column. In your example those two fake getters could be public String getTheRoles() and public String getTheLocations(). Then you can use bean.addNestedContainerProperty("theRoles") and bean.addNestedContainerProperty("theLocations").
In my example my TeamMember class (the counterpart to your Role / Location classes) would still look like in the option above:
public class TeamMember {
private String firstName;
private String lastName;
private Integer age;
// getters and setters
}
And my Team class (your LocationBasedRole) would look like:
public class Team {
private String teamName;
private Set<TeamMember> teamMembers;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public Set<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(Set<TeamMember> teamMembers) {
this.teamMembers = teamMembers;
}
public String getMembers() {
if (teamMembers != null) {
return teamMembers.stream()
.map(member -> member.getFirstName() + " " + member.getLastName())
.collect(Collectors.joining(","));
} else {
return "No members";
}
}
}
Now you can tell vaadin to add the (not existing) property "members" and Vaadin will find the getter getMembers and use this for generating the column. We also have to tell vaadin not to display the original "teamMembers" property. So the final code is:
protected Component createContent() {
Set<Team> teams=new HashSet<>();
for (int teamCounter = 0; teamCounter < 5; teamCounter++) {
Team team = createTeam();
addMembersToTeam(5, team);
teams.add(team);
}
BeanItemContainer<Team> bean=new BeanItemContainer<>(Team.class);
bean.addNestedContainerProperty("members");
bean.removeContainerProperty("teamMembers");
bean.addAll(teams);
teamTable.setContainerDataSource(bean);
return new VerticalLayout(teamTable);
}
and the result looks like:
I have a class PubmedReference that has in addition to some public getters and setters a static method called fromArticle:
public class PubmedReference extends Reference {
#NotNull
#Pattern(regexp = "^[0-9]+$", message = " allows only numbers.")
private String pmid;
private String title = "";
private String authors = "";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
#BsonIgnore
public static PubmedReference fromArticle(PubmedArticle pubmedArticle) {
...
}
#BsonIgnore
public PubmedArticle getFromArticle() {
return null;
}
First thing that is causing confusion is that I have to add a dummy getFromArticle() annotated with #BsonIgnore. Second despite of #BsonIgnore the Mongo Java driver requires me to register all POJOs for the PubmedArticle.class which is like > 20 classes, despite that it should ignore it anyway. Is this a bug in the driver or did I miss anything? I thought static routines are ignored? I'm using MongoDB Java Driver 3.6.3.
Thanks for helping me clarify this.
I'm using Spring Data Neo4j 4.0.0 with Neo4j 2.2.1 and I'm trying to create a relationship between two nodes with the exact same labels.
So, I have a NodeEntity class and I have a variable inside with the same Type as the class itself, and annotate it as Relationship.
But, when I save the object to the database using the save() method of the repository object, the relationship can't be created.
Thank you in advance and your suggestion would be really appreciated!
EDIT
Here is the node entity classes
public class ArchitectureUnitState extends UnitState {
public ArchitectureUnitState()
{
super();
}
public ArchitectureUnitState(String name, String description, String parentArchitectureUnitName)
{
super(name, description);
this.parentArchitectureUnitName = parentArchitectureUnitName;
}
#Relationship(type="PART_OF", direction = Relationship.OUTGOING)
private ArchitectureUnitState architectureUnitState;
#Relationship(type="STATE_OF", direction = Relationship.OUTGOING)
private ArchitectureUnit architectureUnit;
#Transient
private String parentArchitectureUnitName;
public void partOf(ArchitectureUnitState architectureUnitState) {
this.architectureUnitState = architectureUnitState;
}
public void stateOf(ArchitectureUnit architectureUnit) {
this.architectureUnit = architectureUnit;
}
public void childOf(String parentArchitectureUnitName) {
this.parentArchitectureUnitName = parentArchitectureUnitName;
}
public String getParentName() {
return parentArchitectureUnitName;
}
}
#NodeEntity
public class UnitState {
#GraphId
protected Long id;
private String name;
private String description;
public UnitState() {
}
public UnitState(String name, String description) {
this.name = name;
this.description = description;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
}
So, the sequence is: I created the ArchitectureUnitState objects, map one to another, then save with the save() method of the ArchitectureUnitStateRepository.
If I do like this, the PART_OF relationships aren't created, although I see in the debugging that the values are there.
My workaround right now is I save all the ArchitectureUnitState nodes first, retrieve them again from the database, map one to another, then save it again. This way, the relationships can be created, but I need to save two times.
Here's my test case using your classes above.
#Test
public void testArchitectureState() {
ArchitectureUnitState state1 = new ArchitectureUnitState("one","desc one","root");
ArchitectureUnitState state2 = new ArchitectureUnitState("two","desc two","root");
ArchitectureUnit unit1 = new ArchitectureUnit("unit1");
ArchitectureUnit unit2 = new ArchitectureUnit("unit2");
state1.partOf(state2);
state1.stateOf(unit1);
state2.stateOf(unit2);
architectureUnitStateRepository.save(state1);
state1 = architectureUnitStateRepository.findByName("one");
assertEquals("two", state1.getArchitectureUnitState().getName());
assertEquals("unit1", state1.getArchitectureUnit().getName());
state2 = architectureUnitStateRepository.findByName("two");
assertNull(state2.getArchitectureUnitState());
assertEquals("unit2", state2.getArchitectureUnit().getName());
}
It does pass as expected, and the nodes created in the graph appear to indicate the same.
Note that assertNull(state2.getArchitectureUnitState()); holds true because the direction of the relation is specified as OUTGOING. There is no outgoing PART_OF relation from state2, so none will be loaded.
If I change the test to
#Test
public void testArchitectureBothWays() {
ArchitectureUnitState state1 = new ArchitectureUnitState("one","desc one","root");
ArchitectureUnitState state2 = new ArchitectureUnitState("two","desc two","root");
ArchitectureUnit unit1 = new ArchitectureUnit("unit1");
ArchitectureUnit unit2 = new ArchitectureUnit("unit2");
state1.partOf(state2);
state2.partOf(state1);
state1.stateOf(unit1);
state2.stateOf(unit2);
architectureUnitStateRepository.save(state1);
state1 = architectureUnitStateRepository.findByName("one");
assertEquals("two", state1.getArchitectureUnitState().getName());
assertEquals("unit1", state1.getArchitectureUnit().getName());
state2 = architectureUnitStateRepository.findByName("two");
assertEquals("one",state2.getArchitectureUnitState().getName());
assertEquals("unit2", state2.getArchitectureUnit().getName());
}
then we have a relationship in both directions and now state2 has a relationship to state1.
Basic Hibernate question.
I have a class called Song and a class called Artwork, both exist independently. Then an instance of Song can contain multiple Artworks and when they do there are attribute particular to that relationship so I have created another class called CoverArt that links between the two. I'm using annotations for the hibernate stuff and having problems.
If I annotate all three classes as #Entity when I build the database I get the error >'org.hibernate.MappingException: Could not determine type for: Artwork, at table: CoverArt, for columns: [org.hibernate.mapping.Column(artwork)]'
If I change CoverArt to #Embeddable, as it only exists in the context of a Song I get the error
'org.hibernate.annotations.common.AssertionFailure: Declaring class is not found in the inheritance state hierarchy: com.jthink.songlayer.CoverArt'
I can't work out what these messages are saying, what I have wrong. Here is the relevant code from the three classes
Song:
#Entity
public class Song
{
#Id
#GeneratedValue
private Integer recNo;
#ElementCollection(fetch=FetchType.EAGER)
#IndexColumn(name = "POSITION")
private List<CoverArt> coverArt;
.....
CoverArt:
#Embeddable
public class CoverArt
{
private String imageType;
private String description;
private Artwork artwork;
#Id
#GeneratedValue
private Integer id;
public CoverArt()
{
}
public String getImageType()
{
return imageType;
}
public void setImageType(String imageType)
{
this.imageType = imageType;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Artwork getArtwork()
{
return artwork;
}
public void setArtwork(Artwork artwork)
{
this.artwork = artwork;
}
}
Artwork:
#Entity
public class Artwork
{
public Artwork()
{
}
public Artwork(byte[] imageData)
{
this.imageData=imageData;
}
#Id
#GeneratedValue
private Integer id;
#Lob
private byte[] imageData;
private String mimeType;
private int width;
private int height;
public byte[] getImageData()
{
return imageData;
}
public void setImageData(byte[] imageData)
{
this.imageData = imageData;
}
public String getMimeType()
{
return mimeType;
}
public void setMimeType(String mimeType)
{
this.mimeType = mimeType;
}
public int getWidth()
{
return width;
}
public void setWidth(int width)
{
this.width = width;
}
public int getHeight()
{
return height;
}
public void setHeight(int height)
{
this.height = height;
}
}
The CoverArt class should be an entity.
The Song has a list of CoverArt instances, you should thus have
#OneToMany
#JoinColumn(...)
private List<CoverArt> coverArts; // note the final s, since it's plural
Each CoverArt links to an Artwork, so you should also have an association. It's not clear if it's a ManyToOne or a OneToOne, tough. I'll suppose it's a OneToOne:
#OneToOne
#JoinColumn(...)
private Artwork artwork;
It's pretty simple. Each time an entity has a reference to another entity, or a collection of another entity instances, you have an assosiation. And an association can be a OneToMany, OneToOne, ManyToOne or ManyToMany. You have to tell Hibernate which one it is. If you don't tell it, it assumes it's a simple Column which is wrong.
First of all You should tell us how do You want all that to look like in database.
I assume You want something like that:
table 'songs'
table 'artworks'
table 'cover_arts' with fkeys: song_id and artwork_id
So a Song "has many" CoverArts and each CoverArt "has one" Artwork.
If this is correct, then:
Annotate CoverArt with #Entity instead of #Embeddable
inside CoverArt class annotate field 'artwork' with #ManyToOne
replace #ElementCollection on field 'coverArt' inside Song class with #OneToMany. It would be nice to rename field 'coverArt' to 'coverArts' as it is a collection, not a single instance.
Recently I've started hearing about "POJOs" (Plain Old Java Objects). I googled it, but still don't understand the concept well. Can anyone give me a clear description of a POJO?
Consider a class "Person" with variables "id, name, address, salary" -- how would I create a POJO for this scenario? Is the code below a POJO?
public class Person {
//variables
People people = new People();
private int id;
private String name;
private String address;
private int salary;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getSalary() {
return salary;
}
public void setId() {
this.id = id;
}
public void setName() {
this.name = name;
}
public void setAddress() {
this.address = address;
}
public void setSalary() {
this.salary = salary;
}
}
A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:
Default no-arg constructor
Follow the Bean convention of getFoo (or isFoo for booleans) and setFoo methods for a mutable attribute named foo; leave off the setFoo if foo is immutable.
Must implement java.io.Serializable
POJO does not mandate any of these. It's just what the name says: an object that compiles under JDK can be considered a Plain Old Java Object. No app server, no base classes, no interfaces required to use.
The acronym POJO was a reaction against EJB 2.0, which required several interfaces, extended base classes, and lots of methods just to do simple things. Some people, Rod Johnson and Martin Fowler among them, rebelled against the complexity and sought a way to implement enterprise scale solutions without having to write EJBs.
Martin Fowler coined a new acronym.
Rod Johnson wrote "J2EE Without EJBs", wrote Spring, influenced EJB enough so version 3.1 looks a great deal like Spring and Hibernate, and got a sweet IPO from VMWare out of it.
Here's an example that you can wrap your head around:
public class MyFirstPojo
{
private String name;
public static void main(String [] args)
{
for (String arg : args)
{
MyFirstPojo pojo = new MyFirstPojo(arg); // Here's how you create a POJO
System.out.println(pojo);
}
}
public MyFirstPojo(String name)
{
this.name = name;
}
public String getName() { return this.name; }
public String toString() { return this.name; }
}
POJO:- POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification.
Properties of POJO
All properties must be public setter and getter methods
All instance variables should be private
Should not Extend prespecified classes.
Should not Implement prespecified interfaces.
Should not contain prespecified annotations.
It may not have any argument constructors
Example of POJO
public class POJO {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
A POJO is a Plain Old Java Object.
From the wikipedia article I linked to:
In computing software, POJO is an
acronym for Plain Old Java Object. The
name is used to emphasize that a given
object is an ordinary Java Object, not
a special object, and in particular
not an Enterprise JavaBean
Your class appears to already be a POJO.
POJO class acts as a bean which is used to set and get the value.
public class Data
{
private int id;
private String deptname;
private String date;
private String name;
private String mdate;
private String mname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMdate() {
return mdate;
}
public void setMdate(String mdate) {
this.mdate = mdate;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
}
When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.
Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.
Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.
According to Martin Fowler
The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.
Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.
Each variable in a POJO should be declared as private.
Default constructor should be overridden with public accessibility.
Each variable should have its Setter-Getter method with public accessibility.
Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).
And according to Java Language Specification, a POJO should not have to
Extend pre-specified classes
Implement pre-specified interfaces
Contain pre-specified annotations
However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.
A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.
Read more on Plain Old Java Object (POJO) Explained.
there are mainly three options are possible for mapping purpose
serialize
XML mapping
POJO mapping.(Plain Old Java Objects)
While using the pojo classes,it is easy for a developer to map with the database.
POJO classes are created for database and at the same time value-objects classes are created with getter and setter methods that will easily hold the content.
So,for the purpose of mapping in between java with database, value-objects and POJO classes are implemented.
import java.io.Serializable;
public class Course implements Serializable {
protected int courseId;
protected String courseName;
protected String courseType;
public Course() {
courseName = new String();
courseType = new String();
}
public Course(String courseName, String courseType) {
this.courseName = courseName;
this.courseType = courseType;
}
public Course(int courseId, String courseName, String courseType) {
this.courseId = courseId;
this.courseName = courseName;
this.courseType = courseType;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseType() {
return courseType;
}
public void setCourseType(String courseType) {
this.courseType = courseType;
}
#Override
public int hashCode() {
return courseId;
}
#Override
public boolean equals(Object obj) {
if (obj != null || obj instanceof Course) {
Course c = (Course) obj;
if (courseId == c.courseId && courseName.equals(c.courseName)
&& courseType.equals(c.courseType))
return true;
}
return false;
}
#Override
public String toString() {
return "Course[" + courseId + "," + courseName + "," + courseType + "]";
}
}
public class UserInfo {
String LoginId;
String Password;
String FirstName;
String LastName;
String Email;
String Mobile;
String Address;
String DOB;
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getMobile() {
return Mobile;
}
public void setMobile(String mobile) {
Mobile = mobile;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
}
File-setting-plugins-Browse repositories
Search RoboPOJOGenerator and install, Restart Android studio
Open Project and right click on package select on Generate POJO from JSON
Paste JSON in dialogbox and select option according your requirements
Click on Generate button
If a class is not bogged down from a framework or a library, then an object created from that class is recognized as a POJO.
Let's see some examples:
class MyServlet extends HttpServlet{
//....
}
The sole meaning of MyServlet class is given by the HttpServlet class. Therefore the objects created from the MyServlet are not POJOs.
class MyClass implements Serializable{
//...
}
The Serializable interface does not give a meaning to the class MyClass. Therefore the objects created from the MyClass are POJOs.