How does updating work with Ebean and Play framework - java

I'm new to play framework, Ebean, and ORMs in general and I have a question regarding updating fields of a persisted object.
I know that in hibernate when you call the set method of an object, it will automatically call the update method to update in the db. Does Ebean work similarly? With play framework, from what i've read, the getters and setters are generated automatically when the fields are made public. Say I have the following class in my play project:
#Entity
public class Foo extends Model{
public String bar;
}
public static void main(String a[]){
Foo f = new Foo();
f.bar = "foobar";
}
My question has 2 parts:
1) does the assignment f.bar="foobar"; recompile into calling f.setBar("foobar"); within play?
2) And if so, will this assignment automatically call the model's upadte method or do i need to explicitly make update methods for updating each field?
Thanks for the assistance :)

Yes, play creates setter and getters automatically unless you define your custom setters or getters.
In order to persist your data, you have to call model.save() or model.update(), assignments does not automatically update the database.
By the way, I advice you to always write setter and getter for #ID fields, because sometimes it causes very strange errors.

Related

variable id might not have been initialized Spring Boot Controller with lombok

I am trying to add a simple controller method, but I am running into the following
Exercise.java:[13,1] variable id might not have been initialized
Here is the code that I am working with
#RequestMapping(value = "/exercises/{id}")
public ResponseEntity<Optional<Exercise>> getExerciseById(Model model, #PathVariable Integer id) {
Optional<Exercise> exercise = exerciseRepository.findById(id);
if(id!=null)
return new ResponseEntity<Optional<Exercise>>(exercise, HttpStatus.OK);
else
return new ResponseEntity<Optional<Exercise>>(exercise, HttpStatus.NOT_FOUND);
}
I am using an Optional<Exercise> here because I am taking advantage of the build in method findById from the JpaRepository package. I haven't found any good posts on how to handle this is. This is probably something simple. I've found some documentation around this:https://www.java67.com/2016/07/how-to-fix-variable-might-not-have-been-initialized-error-in-java.html, but I could use a little help understanding the best way to fix this. This is the exercise classe
#Entity
#Table(name = "exercise")
#Value
#NoArgsConstructor
public class Exercise {
#Id
#NonNull
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private int chapterId;
private String exercise;
private String answer;
private String question;
private String a;
private String b;
private String c;
}
tldr;
I don't think JPA plays well with the immutable entity created by #Value. Use #Data instead.
ihnbtdttrt (i have nothing better to do than to read this);
This partially guesswork, but since it has seemed to help, this is what I think is happening:
When you call findById(), JPA creates a new entity object using a no-argument constructor, and then sets the fields individually afterwards. (I'm not sure if it uses setters or sets the fields directly using reflection).
The #Value annotation, as documented here, makes a class immutable, with all the fields private and final and with no "setters" created. This means that the only way to set the fields is by passing the field values into a constructor with appropriate arguments. After that the fields are not changeable.
Since JPA initializes entities using the no-args constructor and tries to set the fields afterwards, with your setup, it uses the no-args constructor and ends up with an entity object where none of the fields have been initialized but none of them are modifiable after the constructor. All private, final fields, with no setters. Then it tries to call entity.getId(), and the id field hasn't been initialized, leading to the above error.
To fix this, you can use the #Data annotation instead of #Value. This is similar, but doesn't create an immutable object. In particular, it generates "setter" functions and the fields are not set to final. This is the type of Java bean that JPA expects, one that can be initialized with a no-argument constructor and then have the fields set afterwards.
There may be ways to configure JPA to create objects differently, so that it passes all the data into a constructor so that you can have immutable entities. I know that some Spring DI stuff is configurable to initialize using rich constructors like this, but Idk about JPA.
For what it's worth, I appreciate the value of immutable objects for clean code, but it's not uncommon to find the above pattern of no-arg construction + post-construction setting when using the popular Java frameworks like JPA/Hibernate, Spring, etc. They don't always play well with immutability.

Difference between constructor and getter and setter

I have been doing assignments for college projects. At one point, I am getting confused at what is actually the use of getter and setter when you can actually use constructor methods to achieve the same results. I have searched and found many answers but not satisfactory explanation.
I have laptop.java as follows
public class laptop {
private String model;
public laptop(String brand){
model=brand;
}
public String toString(){
return "Laptop Brand is: "+ model;
}
}
and the laoptopRecords.java that is calling constructor as
public class laptopRecords {
public static void main(String[] args) {
// TODO Auto-generated method stub
laptop laptop1=new laptop("Dell");
System.out.println(laptop1);
}
}
Here I am not using the getter and setter methods and I get desired result for every laptop object.
If I do in another way using getter and setter methods in laptopRecord.java as follows, I get the same result. But I am not getting what is use of getter and setter methods if actually we can achive the results with constructor as well.
laptop.java with getter and setter
public class laptop {
private String model;
public laptop(String brand){
model=brand;
}
public void setlaptop(String brand){
model=brand;
}
public String getlaptop(){
return model;
}
public String toString(){
return "Laptop Brand is: "+ model;
}
}
Getters are always nice. If you forgot what brand you set at creation, it would be nice to have a way of getting it out of that object. What if you got that object from somewhere else? Figuring out the brand using a getter is easy that way. But getters should only be available on directly exposed values. No need to create a getter for internalVersionString if it should not be publically known. But having a getter for colour would be nice... after all, you can see the colour by looking at the laptop (which is a bad analogy for OOP, but it's fitting here IMHO).
Regarding setters... if you have only one attribute, there is not much of a (visible) difference indeed. But what lies beyond that is a deeper subject... mutability. Of course, using a constructor has a greater overhead than simply setting the attribute (getting memory for a whole new object vs. getting memory for a string).
A nice example of not using setters is the String class in Java. A Java String is immutable; once created, it cannot be changed whatsoever. If you want to replace characters or remove some parts, what you get is not a changed String, but instead a brand new String with the desired changes made. But what if you had a class called TextDocument, that contained a whole file's worth of data? Having no ability to replace parts of that one without creating a whole new TextDocument could be hindering.
Having setters automatically means your object is mutable; that means, your object is not fixed upon creation, but can be changed later on. An ArrayList would be a nice example here. You'd certainly not want to allocate a whole new list only to change a single value.
The difference between mutable and immutable are not as clear when using simple cases like your laptop class. Using immutable classes comes in handy when doing parallel work, using mutable classes comes in handy when handling big objects with a large amount of memory needed to allocate.
There's no one-fits-all solution for that problem. But for exposed attributes which should be directly changeable, a setter would be convenient instead of having to construct a whole new object. Imagine a class with multiple attributes... taking your laptop for example, having a brand, a size, a colour and whatnot. If you just want to change the colour, having to construct a new laptop and copying over all the other attributes would be tedious, wouldn't it? A setter would make life easier for you in that case. Just call yourLaptop.setBrand("Dill"); and continue using that laptop. No reason to spend 500 bucks (or rather... bytes) for another one.
I tell you an easy way:
getters() and setters():
actually getters() and setters available in POJO/Bean classes.
The main reason used for getters() setters() in java classes is To get the Java Encapsulation Mechanism.
In POJO/Bean classes we declare all attributes as a private. that means these class attributes can't use in other classes and packages, so in this, we can achieve Encapsulation.
Constructors():
I think you know the definition of constructor, The constructor is used for initializing the attributes giving our own values rather than storing the default values
We can say another way i.e Constructor used for creating an object and setters used for changing the values inside object, getters() user for getting the values, this is only the main difference.
When you extend a class having private data members ,then getters and setters method will help you to access that data members in subclass.While constructor only initialize the data members.
Constructor is used to initialize object.
When we use parameterized constructor to pass parameter it only call once.
Means you can only pass parameter once.
if you call it more then 1 time each time a new object created in memory.
While getter and setter can be called according to your use many time to set or get values

How to initialize field with default constructor using annotation

guys! Could you tell me please, how we can to initialize field, using annotation?
For example:
We have few custom classes: Foo; Bar. And in Main class, we entered two fields
public class Main {
Foo foo;
Bar bar;
}
I want to create annotation, which helps to initialize these fields. In final result I want to see something like this:
#Initialize
Foo foo;
#Initialize
Bar bar;
Annotation itself does nothing. It is just a metadata that can be retrieved using reflection. So, you can implement a kind of factory that receives class, creates its instance using default constructor, discovers the class's fields annotated with your annotation and sets the fields' values.
However I'd as the following questions before starting the implementation:
where will this factory find the values of foo and bar (probably from some kind of repository? Probably from JNDI?)
Do you really need this? Probably initialization using constructor is better. In this case you can mark all fields final, so you object will be immutable that have a lot of advantages
Are you probably re-inventing the wheel? Take a look on Spring framework. It does what you want and much-much more.

Get and Set Method and the MVC Design Pattern [duplicate]

This question already has answers here:
Get and Set methods in Java. How do they work?
(5 answers)
Closed 7 years ago.
Can somebody tell me or show me something that would make me understand the get and set methods completely? I know some of it already but it still confuses me.
I am trying to learn the MVC Design Pattern but I find it hard because I haven't completely understand this. I thought it was easy but it's not really that easy. Well, at least for me.
Your own example would be appreciated. Thank you in advance guys :)
The Model, View, Controller design pattern is a useful way of decoupling the various components of an GUI driven application. It improves cohesion, which essentially emphasises the responsibility of discrete elements of your software and helps avoid unnecessary overlapping of functionality.
The Model stores what is referred to as 'business logic'. This means it houses all of the data which is core to your application.
The View is what handles the graphical interface. Everything responsible for managing how your graphics are rendered is defined here.
Finally, the Controller handles events. This includes asynchronous events such as whenever a key has been pressed, or the mouse has been moved, or the user has touched their screen. It receives these events and decides what to do with them.
So, how they come together is as follows; the Model defines what needs to be drawn. Any graphics the View needs to render is therefore housed in the Model. This means that any modifications to the Model's data will in turn effect what is drawn on the screen; however, the Model is only really defining what elements need to be drawn, it has no clue how to draw them; just how to manage them and manipulate them. It's the View which can take these elements and in turn use them within a graphical context. The controller on the other hand, handles events and in turn manipulates the contents of the Model. It does this by using a defined set of rules on how each input event will affect certain parts of the Model.
So, in this regard, the Model, View, Controller can be looked at like this:
final Model m = new Model();
final View v = new View(m);
final Controller c = new Controller(m);
Both the Controller and View need access to the Model in order to manage and render the application respectively, but the Model doesn't care about either of them. This is because the Model defines the core data dependencies of your application, which should be transferrable, and work independently of whether it's a component of a GUI or not.
In terms of getter and setter methods, all these do are provide access to a member variable sitting inside a class. So if we were to look inside the View, we would see something like this:
public final class View {
/* Member Variables. */
private final Model mModel;
public View(final Model pModel) {
/* Initialize Member Variables. */
this.mModel = pModel;
}
public final Model getModel() {
return this.mModel;
}
}
The method getModel() is referred to as a getter method; it's sole responsibility is to return a variable; in this case it returns the View's mModel variable. What's useful about getter and setter methods is that you can control access to that variable; the method can be declared public, protected and private for example, which all change just who else inside your application can get access to the Model. The same goes for a setter method, whose only responsibility should be to change the value of a specific variable belonging to the owning Object.
I know this should be a comment, but I currently don't have the reputation required to post a comment.
First of all, could you please provide more information about what specifically you'd like to know? Are you confused about how getters and setters work in general? Are you confused about how the work in an MVC pattern? (getters and setters work the same way in MVC as they do in other design patterns).
If the link posted in the comment above doesn't solve your answer, then hopefully I can help. Getters and setters (getVarName and setVarName) are used to provide additional functionality (like ensuring that a value fits a desired range, etc) and also to provide encapsulation of your code. Besides the additional functionality (like validation), encapsulation also helps avoid errors like accidentally changing the value of a class's variable when you don't mean to. Take a Customer class for example:
public class Customer {
private int empNo;
private int deptNo;
//additional class variables
public Customer() {
//default constructor }
public Customer (int emp, int dept) {
empNo = emp;
deptNo = dept;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int emp) {
empNo = emp;
}
//other methods
}
Let's say that all employee numbers must be 5 digits long and not start with a 0. If we don't use a setter, then there's no way to check if the number given is a valid number (or that it was even given). For that, we could write a simple validation requirement in our setEmpNo method.
public void setEmpNo(int emp) {
if(emp >= 10000 && emp <= 99999) {
empNo = emp;
}
//code to handle invalid numbers
}
Encapsulation also helps us avoid certain errors, like changing the value of empNo when we mean to just check the value in a condition, etc. For instance, if we don't use getters and setters and just have a public empNo, the following typo would change the value of the employee's employee number:
if(employee1.empNo = 12345) { //checking if this is employee 12345 would use ==
//perform action for specified employee
}
However, if we use getters and setters, we'd still run into a problem because we're not checking if the desired employee's employee number is 12345, but that employee's number would NOT be permanently changed to 12345 and would still retain his/her correct employee number. Does this make sense?
It looks like someone already posted a pretty good answer about MVC, so I won't repeat any info on that. One thing I will point out is that MVC is usually (if not always) used for server-based apps. If you have an app that contains a website that users interact with and a database, then there's a good chance you'll use some variant of the MVC pattern. However, you're not going to use MVC for something like a Hello World app.
I hope my answer isn't too basic. It's hard to judge a user's knowledge level without getting additional info. If you'd like me to clarify or give further explanation on anything I've posted, let me know.
Best of luck going forward.
Getter and setter methods used when we define instance variables private so from outside class we can't access private instance variables directly which is useful for encapsulation(hiding data from outside world). So for accessing private variables we required some methods which is basically getter and setter.
public class Employee
{
private int empNum;
public Employee(int empNum) {
this.empNum = empNum;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int empNum) {
this.empNum = empNum;
}
}
for more reasons why we use getter/setter read this answer
There is no direct relation between MVC and getter/setter methods.
MVC is basically design patter for software development where we divide task between different modules(model, view and controller)
model -> Data layer
view -> Representational layer
controller -> Controller layer between model and view
So when you create model class in mvc you define multiple instance variables(attributes) for model but from controller you don't want to access that variables directly so in that case you should use getter setter methods.
Actually getter/setter concept in not limited to just mvc it is use as a codding standard and for abstraction purposes.

why we use set method [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the point of setters and getters in java?
I have a question about set method. Please provide some details if possible.
I want to know why do we use set method with class name.
public class Mymainclass {
Private class ClassC {
Private Mysecondclass sec = null;
public void setMymainclass(Mysecondclass second){
Mymainclass.sec= second;
}
}
}
Is it just setting the sec variable value ? if yes why there is class name with set?
It seems like you are confusing a "class constructor" with a "setter method" in a class.
The primary reason for a constructor is to intialize the class variables
The primary reason for a setter method is to access private variables inside the clas
So in your case the name of the method should be "setSec" rather than setMainClass.
That is if you would like to modify the private variable "sec" after you have initialized the class then you can choose to use a setter method.
On the other hand you can also not use a setter method and just have the sec variable be initialized when the class is first created. To do that you will have to create a constructor.
Your constructor for this class will look like this:
Mymainclass(Mysecondclass sec){
this.sec = sec;
}
This way you can pass is a Mysecondclass object as soon as you create a new instance of Mymainclass.
Also try to make sure when you label classes to make each word in the class name to have its first letter capital like this: MySecondClass and MyMainClass!!
Firstly your method should be called "setSeconds" if you follow good practice. Just think how confusing it would be if you added a minutes member to your class.
There are two main reasons for coding setters and getters.
The first is purly pragmatic. If you want to invoke the magic of introspection and java beans then you need to follow these conventions. There are several libraries/APIs like FreeMarker that absolutly depend on haveing getter and setter methods in your class.
The second has more to do with good design. Consider thet you have a public member called seconds. Any user of you class could set this by coding.
instanceOfYourClass.seconds = 60;
This is just fine except maybe you want to impose an arbitary limit of 42 seconds on this value. To validate the value and set it a max of 42 seconds you now need a method to do this. So every user of you class must now change thier code to:-
instanceOfYourClass.setSeconds(60);
So by building in getters and setters from the start you are building in both the flexibilty to do more exotic things within your class, while at the same time providing a stable interface to your class users which wont rquire them to change thier code every time there is a small change in functionality.
I think part of the source of your confusion is that the example you gave is bad code! You don't name a setter based on the class of its argument, you named it based on the property of the object that you're setting. e.g., the canonically 'correct' version of your example would be:
public class Mymainclass {
private Mysecondclass sec= null;
public void setSec(Mysecondclass second){
this.sec= second;
}
}
Having setters that map to property names allows all kinds of different frameworks from UI to persistence and all in between to manipulate your objects in an abstract way. If you tell, for example, your database layer that the property named 'sec' maps to a particular database column, it can use reflection to find the method named "setSec" and set it for you!
The idea of having lots of methods just named 'set' also breaks down when you have lots of properties of the same type, lots of Strings, lots of BigDecimals, whatever. It would be really wierd if there were two standards to only use 'set' when you can and use the property name when you have to. (and you'd find yourself refactoring away those 'set' only methods awfully often.)
In object oriented programming, a good practice is to expose getters and setters to allow other class to interact with a class content instead of making member variables public.
Even if most of the time, at least in the very first version of the class, there won't be much more there than the actual assignment statement, this will allow you to add other behaviors later:
add logging traces to know when and how a new value has been set
do some controls/transformations on the value that is passed before really assign it (what if the other class provided null ?)
trigger some other actions that could be necessary whent this new assignment is done
...

Categories

Resources