How to edit(add) something already saved in a database table column? - java

I'm using java and I have a software that registers a patient and save it in a database, but there are some attributes that must be changed every time and I dont know how to do it:
My table(patients):
1.Name: (patient's name) [varchar].
2.CPF:(is a personal number that Brazilians uses to identify yourself, everybody has one), [varchar].
3.Notes:(patient's progress after the scessions) the patient will receive a bunch of notes, so it should be an array.
After one note saved, I would like to save more after...

As after the update, you Need to update the notes for the patient. So what you can do is create a table called Patient_Notes where it will have the reference from the patient table (patient_id). By this, you can store all the notes for the patient. And also you won't need to update the same. You can just fetch the last one and also you will the have the records for all the notes that have been made.

Related

Observing #Relation changes in a DataBase

If I something like the following:
#Relation(parentColumn = "id", entityColumn = "fk_id", entity = User.class)
private List<User> users;
This list is a model which gets updated via LiveData.
But I want to be able to update this when I detect changes to the User table. Right now, it only picks up what exists in the DB, but whenever an update happens to the user table, this list does not get updated. Any suggestions?
You have not been very specific in what you are doing or want (which database you use, who is updating the database...).
But I want to be able to update this when I detect changes to the User
table. Right now, this only picks up what exists in the DB but
whenever an update happens to the user table, this list does not get
updated. Any suggestions?
Option 1
If you are doing the update/insert/delete in the same app as the List users, then you can easily update your List in your code.
Option 2
If another app/service is updating the database, I suggest you use a trigger to update your List.
See http://www.coderconsole.com/2015/02/android-sqlite-trigger-demo.html for an example.
Detecting the change in Java is tricky, see Calling a Java method from a sqlite trigger (android) .
Here is an example where you use a ContentObserver to monitor your Sqlite database (the flat file itself) https://gist.github.com/JBirdVegas/3874450
Option 3
If another app/service is updating the database, you can use a BroadcastReceiver to pick up the changes.

Automatically expire and delete record in SQLite database

I'm am fairly new to android and I made an app that creates, modifies and deletes users using SQLite. What I want to do is that after, lets say a week after a user is created, it deletes itself without the administrator having to do it himself.
Is there a way to do this? Thank you for your answers
You'll have to store a creationDate with the user then make a service that runs sql command, let's say each night, to see wich users are more than a week old.
I don't think there is a way that the database detects it alone.
Here is a link about AlarmManager it's usefull to run background stuff at set times.
So I created two rows in my SQLite DB and made a timestamp with the current date.
The second row was a TEXT and I made the user pick the expiration date using a CalendarView.
To delete the row I used the delete method. Since this method return an int value, I made it launch a Toast to say how many rows where deleted

Possible overwriting to database table

Let's say you have a database table name table1 with columns name and surname. Two different clients open the same view from the java application and get the data for same person at the same time.
1) First client changed the name and pressed save button to update database record.
2) Client2 still sees the old record on the screen and then pressed to save button to change the surname.
It actually overwrite the record by old name. I think to check and get the latest data before updating the database when I click button but I do not like this solution because of making a second query before update.
So how can we solve this problem by using Hibernate and without using Hibarnete. Any idea?
Of course if you do not want that something will be overridden, then you have to check the data before an update. But it will be not always a real query with a good caching strategy. You could also use a timestamp with last update to compare it easier. Another strategy would be to lock the entities when the first user will read them. But that is normally not a good design for web applications or you have to integrate a messaging service, which will all user inform for an update who actually have open that entity. But I think that is not so easy to implement and a more advanced feature.
In short, compare the timestamp of an entity and if already updated, then compare the changes and show them for the user who wanted update that entity.

relationship and build database

For an excercise I need to build something like :
For a course I need to create a review that is made up out of certain reviewlines and feedbackscores.
This review object (unique instance) needs to be filled in by a list of customers.
Depending on the course the review is for, the review will change (e.g.for one course the number of reviewlines and feedbackscores will change). Each customer can be enrolled in more then one course and each review is specific for him.
Now how do I need to see the relationsship between "review" object (unique instance) and "customer" if I want to use JPA to save this all to the db?
A customer can have more then one review he/she needs to fill in.
A certain review object needs to be filled in by many customers (but this is a review object with a certain build [reviewlines and feedbackscores]) and unique for him.
Maybe I see it to complex but what is the best way to build this?
Try the following:
I think it's covered all your design points.
I am trying to read between the lines of your comments, and I think you want to implement a system where you capture a number of 'rules' for the Review (I'm guessing, but examples may be that reviews can be up to n lines, there must be at least m CustomerReviews before the Review gains a degree of quality). If this is indeed the case, I have created a ReviewTemplate class:
ReviewTemplate would have attributes/columns for each of value you would need. These attributes/columns are duplicated on Review
Populate ReviewTemplate with a number of rows, then create a row in Course and link it to one ReviewTemplate
When a Course needs a Review, copy the fields from the ReviewTemplate into the Review
In Java, implement the business rules for Review using the copied values - not the values on ReviewTemplate.
Why copy the values? Well, I bet that at some point, users want to edit the ReviewTemplate table. If so, what happens to the Review objects using the edited ReviewTemplates? Does the modified value on ReviewTemplate somehow invalidate past Reviews and break your business logic? No, because you copied the rule values to Review and so past Reviews will not change.
EDIT: Answers to specific questions
How do you see the duplicating? I can create an entity ReviewTemplate with the specified attributes. In this entity there will be a relationship with reviewlines and feedbackscores.
I see each ReviewTemplate as holding prototypical values for a particular 'type' of Review, which just might include a default reviewLine (but that might not make sense) and a default feedbackScore. When you create the Review, you would do the following:
Instantiate the Review and populate with values from ReviewTemplate
Instantiate as many CustomerReview objects as you need, linking them to the relevant Customer objects (I infer this step from your previous comments. It might also make sense to omit this step until a Customer voluntarily elects to review a Course)
(If appropriate) Populate the CustomerReview attribute feedbackScore with the default value from ReviewTemplate
Instantiate CustomerReviewLine records as appropriate
If you follow this approach, you do not need to add a relationship between ReviewTemplate and CustomerReviewLines.
When I e.g. state that customers 1 to 4 need to fill in the review 4 specific "objects" need to be created that will hold the information and also 4 sets of the needed reviewlines and feedbackscores need to be created so they all can hold the information.
Absolutely.
I just don't know how to implement this is a JPA structure so the information is hold in the db ... ?
JPA allows you to attack the problem in many ways, but the best practice is to manually create both the DB schema and the Java classes (eg see https://stackoverflow.com/a/2585763/1395668). Therefore, for each entity in the diagram, you need to:
Write SQL DDL statements to create the table, columns, primary key and foreign keys, and
Write a Java class denoted with the #entity annotation. Within the class, you will also need to annotate the id (primary key) with #id and the relationships with #OneToMany or #ManyToOne (theirs additional parameters in the annotation to set as well).
Now, on the JPA side, you can do things like:
ReviewTemplate template = course.getReviewTemplate(); //assuming the variable course
Review review = new Review();
review.setCourse(course);
review.setRuleOne(template.getRuleOne());
// Copy other properties here
EntityManager em = // get the entity manager here
em.persist(review);
// Assume a set or list of customers
for (Customer customer : customers) {
CustomerReview cr = new CustomerReview();
cr.setReview(review);
cr.setCustomer(customer);
cr.setFeedbackScore(template.getDefaultFeedbackScore());
// set other CustomerReview properties here
em.persist(cr);
// You can create CustomerReviewLine here as well
If written inside a standard EJB Session Bean, this will all be nicely transacted, and you will have all your new records committed into the DB.
EDIT 2: Additional question
(I'm assuming that the second comment completely supersedes the first)
So when I create a reviewtemplate and I link it to a bunch of customers I write the template to the db and create a bunch of reviews based on the template but linked to the specific customer and with his own unique reviewlines and feedbackscores. Like I see it now the reviewline (more a question or discription) is the same for each review (of a template), it is only the score that changes between the customers
I finally think I understand ReviewLine. I had thought it a place where the Customer enters lines of text the comprise the CustomerReview. I now believe that ReviewLine is a specific question that the Customer is asked, and which the Customer provides a feedbackScore.
With this understanding, here is an updated ER/Class diagram.
Note that there are some significant changes - there are several more tables:
ReviewLineTemplate provides a place for template questions to be stored on a ReviewTemplate
When a Review is instantiated/inserted (which is a copy of a specific ReviewTemplate), the ReviewLineTemplates are copied as ReviewLines. The copy operation allows two important features:
On creation, a Review and its ReviewLines can be customized without affecting the ReviewTemplate or ReviewLineTemplate
Over time, the ReviewTemplate and ReviewLineTemplate can be updated, edited and continually improved, without changing the questions that the Customer has already answered. If CustomerFeedbackScore were linked to ReviewLineTemplate directly, then editing the ReviewLineTemplate would change the question that the Customer has answered, silently invalidating the feedbackScore.
FeedbackScore has been moved to a join-table between ReviewLine and CustomerReview.
Note that this model is fully denormalised which makes it more 'correct' but harder to build a GUI for. A common 'optimization' might be to introduce:
10 (say) columns on ReviewTemplate and Review called reviewLine1 through reviewLine10.
10 (say) columns on CustomerReview called feedbackScore1 through feedbackScore10.
Remove the ReviewTemplateLine, ReviewLine and CustomerReviewLine tables
Doing so is not normalised, and may introduce a set of other problems. YMMV
The structure of data always depends on the requirements, and there never exists a "one-and-only" solution. So, do you need maximised atomiticy or a high performance data system?
The fastest and easiest solution would be not using a database, but hash tables. In your case, you could have something like 3 hash tables for customer, review, and probably another one for the n:n relationship. Or if you're using a database, you could just store an array of the review-primary-keys in one field in the customer table.
However, we all learn in school to do atomicity, so let's do that (I just write the primary/foreign keys!):
Customer (unique_ID, ...)
Review (unique_ID, ...)
Customer_Review (customer_ID, review_ID, ...) --> n:n-relationship
The Customer_Review describes the n:n-relationship between customers and reviews. But if there is only one customer per review possible, you'll do that like this:
Customer (unique_ID, ...)
Review (pk: unique_ID, fk: customer_ID, ...) --> 1:n-relationship
However, I suggest you need to learn ERM as a good starting point: http://en.wikipedia.org/wiki/Entity_relationship_model
You need a ManyToMany relation :
One customer -> several reviews.
One review -> several customers.
So you will have 3 tables in your database schema : Customer, review and a junction table with the customer ID and the review ID.
See Wikipedia : Many to Many

How to create an undo function in spring MVC based web app.?

I have an employee and a corresponding employee history table.
Both the tables have same structure. History table is used to track the historical changes made to the employee over a period of time.
Now, I need to add an undo function to the changes made to the employee.
e.g. Employees title is changed on 1st August. Now, This will update the employees title in Employee table and insert an corresponding history record in employee_history table.
Now, I need to undo this change. Employee edit page will have a list of changes made to employee datewise with an undo button beside it.
Clicking on undo should revert changes in Employee table to previous value. Also I think the record in history table which says title is changed, should also be removed.
Also when I revert tghe changes to employee table i.e. revert title to previous title, this will fire an insert to history table, which I dont want.
I am not sure what is the best possible way to do this.
Any suggestions will be helpful.
In case you want to implement a "persistent" undo - one that would survive an application restart/session timeout, you should consider extending your DB schema width timestamp fields and either delete the last entry or replace it with an appropriate earlier entry.
A "light" version would be using a stack to store last interactions, including the original and the new value. You could persist the stack on session invalidation of course to combine both approaches. This seems to be what you are actually doing.
You could extend this solution by creating and storing or exporting SQL migration scripts for each change, recording the change and, if possible, the opposite action. So you could even transfer the scripts between application instances and environments and would have a complete "replayability" of your DB states.
tl;dr - it looks like you have already implemented a good solution
I would suggest using a flag telling the trigger/history logic to keep off while you have your undo running and not writing history data.
Normally this would be done by serializer-class feeding from your history table and restoring employee data and later cleaning up history-entries/unlocking history again.
You could maybe use the rollback feature of the transaction.

Categories