Where to get Java eclipse extention\shourtcut for getters setters generation? - java

So I started to write a POJO class, created public variables and now want to get getters and setters for them (folowing Java Naming Conventions)
so I have for example something like
package logic;
import java.util.Set;
import java.util.HashSet;
public class Route {
private Long id;
private String name;
private int number;
private Set busses = new HashSet();
}
which eclipse extention and in it which shourtcut will create Getters and setters for me to get something like
package logic;
import java.util.Set;
import java.util.HashSet;
public class Route {
private Long id;
private String name;
private int number;
private Set busses = new HashSet();
public Route(){
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(int number) {
this.number = number;
}
public void setBusses(Set busses) {
this.busses = busses;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public Set getBusses() {
return busses;
}
}

I think this is availble by default using Ctrl + Shift + G ( I may have set this shortcut myself)
Or go to the Source menu, and select the Generate Getters and Setters option.
You can modify the keyboard short cut (and many others) by going to
Window->Preferences
Expand the "General" option
Select the "Keys" option

In Eclipse, right click on the source code and choose Source -> Generate Getters and Setters.
This will open a dialog box where you can choose which of the class members you want to generate for. You can also specify either getters or setters only as well as generating Javadoc comments.
I use this all the time, very handy function!

Related

Hibernate: Inheritance strategy, and annotations when persist abstract collections bidirectional

I am struggling with the right combination of inheritance strategy, and associations annotations when trying to persist abstract collections bidirectional with Hibernate.
All attempts I made so far fail, most with the complaint that #ManyToOne references an unknown identity.
Given the below example, the questions I have are
what is the best to maintain hibernate inheritence strategy for the
below structure?
which row id generation fits the inheritence strategy?
how to annotate each of the classes (e.g. #Entity, #MappedSuperclass)?
how to annotate the methods or field definitions (e.g. #ManyToOne, #OneToMany?
Since my code is embedded in a bigger structure and each class is rather big, here is a mock about cars - which is still big. Some relations I would model differently if I would really model cars, but this mock hopefully describes the basic problem in a more digestable form, without all the ballast from my real code.
The relations look like this:
the related java code looks like this:
package persistence;
public abstract class MechanicalObject {
private int weight;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public abstract void someMethod();
}
package persistence;
import java.util.List;
public abstract class Car extends MechanicalObject {
protected List<Engine> potentialEngines; // references to something that also extends MechanicalObject
protected List<Driver> potentialDrivers; // references to something that does not extend MechanicalObject
public List<Engine> getPotentialEngines() {
return potentialEngines;
}
public void setPotentialEngines(List<Engine> potentialEngines) {
this.potentialEngines = potentialEngines;
}
public List<Driver> getPotentialDrivers() {
return potentialDrivers;
}
public void setPotentialDrivers(List<Driver> potentialDrivers) {
this.potentialDrivers = potentialDrivers;
}
}
package persistence;
public abstract class Engine extends MechanicalObject {
private int driveRPM;
private Car parent; // bidirectional reference
public int getDriveRPM() {
return driveRPM;
}
public void setDriveRPM(int driveRPM) {
this.driveRPM = driveRPM;
}
public void someMethod() {
// do something
}
public abstract void anotherMethod();
}
package persistence;
public class Driver {
// db row id
private long id;
private String name;
private String licenceType;
private Car parent; // bidirectional reference
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLicenceType() {
return licenceType;
}
public void setLicenceType(String licenceType) {
this.licenceType = licenceType;
}
public Car getParent() {
return parent;
}
public void setParent(Car parent) {
this.parent = parent;
}
}
package persistence;
public class CombustionEngine extends Engine {
// db row id
private long id;
private int cylinderCapacity;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getCylinderCapacity() {
return cylinderCapacity;
}
public void setCylinderCapacity(int cylinderCapacity) {
this.cylinderCapacity = cylinderCapacity;
}
public void anotherMethod() {
// do something differently
}
}
package persistence;
public class ElectroEngine extends Engine {
// db row id
private long id;
private int nominalVoltage;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getNominalVoltage() {
return nominalVoltage;
}
public void setNominalVoltage(int nominalVoltage) {
this.nominalVoltage = nominalVoltage;
}
public void anotherMethod() {
// do something
}
}
package persistence;
public class TeslaModelX extends Car {
private long id;
private String licenceNumber;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
public void someMethod() {
// do something differently
}
}
package persistence;
public class VWBeetle extends Car {
private long id;
private String serialNumber;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public void someMethod() {
// do something differently
}
}
I would be greatful for any help. Links to web pages that explain the solution are also welcome, as I couldn't find any that handeled this subject completely.
what is the best to maintain hibernate inheritence strategy for the below structure?
That depends on what the rest of your model looks like. The easiest to use strategy would be single-table but if the subclasses differ too much a joined-table strategy or table-per-class strategy might be better. Just read up on those and pick one you're comfortable with. Note, however, that it's hard to change inheritance strategy further down the hierarchy - if it's possible at all (probably depends on the JPA provider).
which row id generation fits the inheritence strategy?
I'd say those are independent as Hibernate should handle that for you. Just pick an id generation strategy that fits your needs. What you'd probably need though is a discriminator column to let Hibernate identify the entity class each row represents.
how to annotate each of the classes (e.g. #Entity, #MappedSuperclass)?
That depends on your needs but I'd assume that Car and Engine aren't that related so they'd be entities while MechanicalObject could be a mapped superclass. Of course, if you want some other entity to reference any MechanicalObject you might have to make it an entity as well, use a different mapping approach or rethink your requirements/model.
how to annotate the methods or field definitions (e.g. #ManyToOne, #OneToMany?
Do as needed and read up on the annotations. Just keep in mind that one side needs to be the owner of the relation, i.e. only changes to that side are persisted on the database. If you don't do that you risk corrupting your model and confusing the JPA provider. The easiest way to do that on bidirectional 1-n relations would be to add mappedBy="..." to the 1-side, i.e. to #OneToMany.
As an example, your Car-Driver relation could look like this:
class Car extends MechanicalObject {
#OneToMany( mappedBy="parent" )
protected List<Driver> potentialDrivers;
}
class Driver {
#ManyToOne
protected Car parent; //I'd use a better name here
}

Spring JPA with boolean fields throws "cannot resolve property exception"

I am facing, "could not resolve property isManager of" Hibernate query exception.
I have the following java class:
public class Employee implements Serializable {
#Column(name = "employee_id")
private Integer employeeId;
#Column(name = "name")
private String name;
#Column(name = "is_manager")
private boolean manager;
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isManager(){
return employeeId;
}
public void setManager(boolean manager) {
this.manager = manager;
}
These are the eclipse generated setters and getters. When I replaced,
public boolean isManager() {
return employeeId;
} with
public boolean getManager() {
return employeeId;
}
The error is gone. I have gone through so many stack overflow examples. But everywhere, it's given, we shouldn't name the field that starts with "is".
Could anyone please explain?
Thanks.
Hibernate use the getXxx and setXxx for the all the variable . So the getter the isManager variable getter getManager() is not available for hibernate.
so it get error. To resolve the issue.
You can generate the your own getter and setter as getManager() & setManager()
You can use the Boolean object instead of primitives.
Note: getIsManager is not meaningful to access the primitive boolean type. So Eclipse generate the getter for all the primitive start with isXXX as a getter.
Thanks for the comments.
I found the solution. When we name the field as isManager with the STS generated setter and getter, default value of Boolean, false is saved in DB.
field shouldn't start with auxiliary verb. According to my example:
#Column(name = "is_manager")
private boolean manager;
public boolean isManager() {
return employeeId;
}
public void setManager(boolean manager) {
this.manager = manager;
}
The above setter and getter works properly. I haven't updated the #param value in DB interface method.
Thanks.

JavaFX bind not property member to control

Imagine I have a POJO like:
public class Person()
{
private int id;
private String name;
public int getId()
{
return this.id;
}
public String getName()
{
return this.name;
}
}
If I need to bind name member to JavaFX label using bind() method, I can't apply because I need and observable value.
I know that I can use StringProperty instead String, but I need primitive types because I use Hibernate and I don't know if Hibernate could support properties from JavaFX to map data from DB.
Which alternatives I have to bind from my pojo to a JavaFX control?
You have a couple of options here.
Firstly, it's possible to use FX Properties in JPA/Hibernate entities, though you have to be a little careful. In short, you need to make sure you use property access so that the ORM calls the get/set methods, instead of trying to set the field directly. Steven van Impe discusses this on his blog, and I also blogged on the same topic. One thing I haven't tried here is mapping collections and using ObservableLists: that might be tricky as JPA implementations use a subinterface of List.
Your other option is to make the properties "bound properties" in the Java Bean sense, and then to use a Java Bean Property Adapter:
import java.beans.PropertyChangeSupport ;
public class Person()
{
private int id;
private String name;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
this.pcs.removePropertyChangeListener(listener);
}
public int getId()
{
return this.id;
}
public void setId(int id)
{
int oldId = this.id ;
this.id = id ;
pcs.firePropertyChange("id", oldId, id);
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
String oldName = this.name ;
this.name = name ;
pcs.firePropertyChange("name", oldName, name);
}
}
Then you can do
Label nameLabel = new Label();
Person person = new Person();
nameLabel.textProperty().bind(JavaBeanStringPropertyBuilder.create()
.bean(person)
.name("name") // name of property to bind to
.build());

Generics in POJO - Is this a good practice

I have a Base Class.
#Data
class BaseDocument{
String id;
String name;
//Other fields
}
Say I have many classes that extends BaseDocument one below.
class NoteDocument extends BaseDocument{
String description;
Long lastModifiedDate;
//etc
}
It does not make sense to me to send entire document to UI in some cases. Most of the cases I need only id and name.
So for every document I have a VO class.
#Data
class BaseVO {
private String id;
private String name;
}
#Data
class NoteVO extends BaseVO{
//Nothing here now
}
And in NoteDocument I have.
public NoteVO getVo(){
Assert.notNull(getId());
NoteVO noteVo = new NoteVO();
noteVo.setName(getName());
noteVo.setId(getId());
return noteVo;
}
Now I have to copy this method in all the classes that extends BaseDocument.
Instead, I changed my BaseDocument like below.
#Data
class BaseDocument<V extends BaseVO>{
String id;
String name;
public V getVo(Class className) {
Assert.notNull(getId());
V vo = null;
try {
vo = (V) className.newInstance();
vo.setName(getName());
vo.setId(getId());
} catch (IllegalAccessException|InstantiationException e){
e.printStackTrace();
}
Assert.notNull(vo);
return vo;
}
}
I am new to generics. My first question, is this a good practice. Are there any problems in using reflection to create instance, any performance issues? Is there any better way to do achieve (write less code) this.
Edit: Suppose I need to display note in UI, Along with note I need to display name of the User who created note. I am using mongodb, when I save the note I also save UserVO in note, which will have user id and name of the user. If I save only user id while saving the note, I will have to do one more query to get the name of user while displaying. I want to avoid this.
Do not use reflection; use inheritance and maybe covariant return types instead. It will be faster, clearer, more precise, and easier to maintain. You may also find it useful to add methods to populate your VOs incrementally. I didn't come up with a clean way to apply generics to this situation, but I don't think you need them:
class BaseVO {
String id;
String name;
void setId(String id) {
this.id = id;
}
void setName(String name) {
this.name = name;
}
}
class NoteVO extends BaseVO {
// ...
}
#Data
class BaseDocument {
String id;
String name;
//Other fields
protected void populateBaseVO(BaseVO vo) {
vo.setId(id);
vo.setName(name);
}
public BaseVO getVO() {
BaseVO vo = new BaseVO();
populateBaseVO(vo);
return vo;
}
}
#Data
class NoteDocument extends BaseDocument {
String description;
Long lastModifiedDate;
// ....
protected void populateNoteVO(NoteVO vo) {
populateBaseVO(vo);
// ...
}
public NoteVO getVO() {
NoteVO vo = new NoteVO();
populateNoteVO(vo);
return vo;
}
}

how to create a dynamic class at runtime in Java

Is it possible to create a new Java file from an existing Java file after changing some of its attributes at runtime?
Suppose I have a java file
public class Student {
private int rollNo;
private String name;
// getters and setters
// constructor
}
Is it possible to create something like this, provided that rollNo is a key element for the table?
public class Student {
private StudentKey key;
private String name;
//getters and setters
//constructor
}
public class StudentKey {
private int rollNo;
// getters and setters
// construcotors
}
Please help. Thanks.
Take a look at javassist.

Categories

Resources