In my Java project there are so many classes and every class requires a common value to display the data like (NT_Login, Country, Location and Role) so for every class I am using the JDBC to get the value from AdminTable(SQL) like NT_Login, Country etc and then it displaying me the result. Am I doing correct ? Or at the starting of the project should I Call JDBC to get the values and then should I pass all the values as a parameter to the other class? I don't know the best possible way please suggest me even if there are other thing which I can try but It should be the standard method as per the Software Development.
//This is what I am doing for all the class
ClassFindAdmin admin = new ClassFindAdmin();
AdminBean bean = admin.getUserDetails(userName);
String country = bean.getCountry();`enter code here`
String location = bean.getLocation();
String role = bean.getRole();
String name = bean.getUser_Name();
If these values are same across a session, then it is better to get the values once and set in session. That way you can avoid to go to the DB all the time.
In my opinion, may be calling all the references from the database, at the initial point of execution is a great idea, which is pointed out by you. In this way, we do not need to look upon the jdbc, frequently. However, this approach may delay the execution of the project. Not sure, what should be the best approach.
Related
I have a situation where i am changing few parameters values of an Object.
UserDetails has around 14 parameters.I am changing the values of few parameters and submitting them from a Form .These values should get updated on the database back-end.
Are there any inbuilt functions to check if any of the values got changed?
Are there any inbuilt functions to say which of the values got changed?
No.
Are there any inbuilt functions to check if any of the values got changed?
No.
However, you can implement your own methods to test these things. An equals method is easy to implement, and indeed many IDEs have "wizards" to generate them. A "what has changed" method is more complicated. The complexity comes in how the method tells the caller what fields have changed, and how the caller can make use of this information.
Alternatively, Apache Commons provides a class called EqualsBuilder that uses reflection, etcetera to compare objects based on their fields.
I also agree with JB Nizet. If you are doing this in an attempt to optimize database updates, you are probably wasting your time. You are probably better off just saving the all of the fields.
Consider this. Unless your front-end caches the old values of the fields read from the database while the user is updating the form (or not), your front end is going to have to re-query the database to find the old value. You would be better off just issuing the UPDATE to update all of the fields than doing a SELECT followed by a conditional UPDATE is something has changed.
Probably you can check this link.. I am not sure this can be done in java. But, you can try with javascript. Please check this link. You can do with EXT.js
handler: function(btn, evt) {
var f = btn.up('form').getForm();
f.submit({
url: '/some-path-on-my-server/save/,
getParams: function(useModelValues) {
var falseVal = false;
var fieldParams = this.form.getValues(falseVal, true, this.submitEmptyText !== falseVal, useModelValues, true);
return Ext.apply({}, fieldParams);
}
});
}
https://www.sencha.com/forum/showthread.php?173867-I-want-to-submit-only-dirty-field-values.
To end 2014 year I got a simple question I think.
I would like to use "DDD" a bit more, and I'm currently trying to experiment various usecases to learn more about DDD.
My current usecase is the following :
we have a new database schema that is using a classic pattern in our company : modeling our nomenclature table as "id / code / label". I think it's a pretty classic case when using hibernate for example.
But in the OO world things get "complciated" for something this simple when using a API like JDBC or QueryDSL. I need to fetch an object by its code, retrieve its id or load the full object and then set it as a one to one relation in another object.
I wondering :
this kind of nomenclature can be an enum (or a class with String cosnatnts depending on the developer). in DDD terms, it is my ValueObject
the id /code / label in the database is not i18n friendly (it's not a prerequisite) so I don't see its advantages. Except when the table can be updated dynamically and the usecase is "pick something in a combobox loaded from this table and build a relation with another object : but that's all because if you have business rules that must be applied you need to know the new code etc etc).
My questions are :
do you often use the id / ocde / label pattern in your database model.
how do your model your nomenclature data ? (country is perhaps not the best example :) but no matter what how do you model it ? without thinking much I would say database table for country; but for some status : "valid, waiting validation, rejected" ?
do you model your valueObjects using this pattern ?
or do you use lots of enum and only store their toString (or ordinal) in the database ?
In the Java OO objects world, I'm currently thinking that it is easier to manipulate enum that objects loaded from the database. I need to build repositories to load them for example. And it will be so simple to use them as enums. I'm searching some recomfort here or perhaps am I missing something so obvious ?
thanks
see you in 2015 !
Update 1 :
We can create a "Budget" and the first one is mark as Initial and the next ones are marked as "Corrective" (with a increment). For example, we can have a list of Budgets :"Initial Budget", "Corrective budget #1", "Corrective budget #2".
For this we have this database design : a Budget Table, a Version Budge with a foreign key between the two. the Version budget only contains an ID, a CODE and a LABEL.
Personnaly, I would like to remove this table. I don't see the advantages of this structure. And from the OO perspective, when I'm creating a budget I can query the databse to see if I need to create an Inital or Corrective budget (using a count query) then I can set the right enum to my new budget. But with the current design I need to query the database using the CODE that I want, select the ID and set the ID. So yes, it's really database oriented. Where is the DDD part ? a ValueObject is something that describe, quantify something. In my case seems good to me. A Version describe the current status of my Budget. I can comapre two versions just but checking their code, they don't have lifecycle (I don't want this one in particular).
How to you handle this type of usecases ?
It's only a simple example because I found that if you ask a database admin he would surely said that all seems good : using primary key, modeling relations, enforing constraints, using foreign key and avoid data duplication.
Thanks again Mike and Doctor for their comments.
I will hook in in your country example. In most cases, country will be a value object. There is nothing that will reference a country entity and that should know that if the values of the country changes it is still the same country. In fact, the country could be represented as an enum, and some nasty resource lookup functions that translate the Iso3 into a usefull display text. What we do is, we define it as a value object class with iso3, displayname and some other static information. Now out of this value object we define a kind of "power enum" (I still miss a standard term here). The class implementing the country value object gets a private constructor and static properties for each of its values (for each country) and explicit cast operators from and to int. Now you can treat it just like a normal enum of your programing language. The advantage to a normal enum beside having more property fields is, that it also can have methods (of course query methods, that don't change the state of the object). You can even use polymorphism (some countries with different behaviour than others). You could also load the content of the enums from a database table (without the statics then and a static lookupByIso3 method instead).
This you could make with some other "enum like" value objects, too. Imagine Currencies (it could have conversion methods that are implemented polymorphic). The handling of the daily exchange rates is a different topic though.
If the set of values is not fixed (for example another value object candidate like postal adress) then it is not a value object enum, but a standard value object that could be instantiated with the values you want.
To decide if you can live with something as a value object, you can use the following question: Do you want copy semantic, or reference semantic? If you ever change a property of the object, should all places where you used it update, too, or should they stay as they are? If the latter, than the "changed" object is a new and different value object. Another question would be, if you need to track changes to an object realizing that it remains the "same" despite of changing values. And if you have a value object, where you only want specific instances to exist, it is a kind of enum described above.
Does that somehow help you?
My question more specificity is this:
I want users on multiple front ends to see the "Type" of a database row. Let's say for ease that I have a person table and the types can be Student, Teacher, Parent etc.
The specific program would be java with hibernate, however I doubt that's important for the question, but let's say my data is modelled in to Entity beans and a Person "type" field is an enum that contains my 3 options, ideally I want my Person object to have a getType() method that my front end can use to display the type, and also I need a way for my front end to know the potential types.
With the enum method I have this functionality but what I don't have is the ability to easily add new types without re-compiling.
So next thought is that I put my types in to a config file and simply story them in the database as strings. my getType() method works, but now my front end has to load a config file to get the potential types AND now there's nothing to keep them in sync, I could remove a type from my config file and the type in the database would point to nothing. I don't like this either.
Final thought is that I create a PersonTypes database table, this table has a number for type_id and a string defining the type. This is OK, and if the foreign key is set up I can't delete types that I'm using, my front end will need to get sight of potential types, I guess the best way is to provide a service that will use the hibernate layer to do this.
The problem with this method is that my types are all in English in the database, and I want my application to support multiple languages (eventually) so I need some sort of properties file to store the labels for the types. so do I have a PersonType table the purely contains integers and then a properties file that describes the label per integer? That seems backwards?
Is there a common design pattern to achieve this kind of behaviour? Or can anyone suggest a good way to do this?
Regards,
Glen x
I would go with the last approach that you have described. Having the type information in separate table should be good enought and it will let you use all the benefits of SQL for managing additional constraints (types will be probably Unique and foreign keys checks will assure you that you won't introduce any misbehaviour while you delete some records).
When each type will have i18n value defined in property files, then you are safe. If the type is removed - this value will not be used. If you want, you can change properties files as runtime.
The last approach I can think of would be to store i18n strings along with type information in PersonType. This is acceptable for small amount of languages, altough might be concidered an antipattern. But it would allow you having such method:
public String getName(PersonType type, Locale loc) {
if (loc.equals(Locale.EN)) {
return type.getEnglishName();
} else if (loc.equals(Locale.DE)){
return type.getGermanName();
} else {
return type.getDefaultName();
}
}
Internationalizing dynamic values is always difficult. Your last method for storing the types is the right one.
If you want to be able to i18n them, you can use resource bundles as properties files in your app. This forces you to modify the properties files and redeploy and restart the app each time a new type is added. You can also fall back to the English string stored in database if the type is not found in the resource bundle.
Or you can implement a custom ResourceBundle class that fetches its keys and values from the database directly, and have an additional PersonTypeI18n table which contains the translations for all the locales you want to support.
You can use following practices:
Use singleton design pattern
Use cashing framework such as EhCashe for cashe type of person and reload when need.
So there is a new guy that has started where I work. I'm quite a junior programmer myself, but I've been developing for a bit longer, so I'm using my "gut feeling" to guide us in developing a project. The blind leading the blind.
A relatively small thing just came up, and I would like to know what is the best way to create this for future reference and why.
Essentially there is a basic XML file with details for files (structure isn't really relevant). He went about querying this XML file and then storing all retrieved files by creating several lists, something like so:
List<Integer> fileId = new List<Integer>;
List<String> title = new List<String>;
And then you would create a method which would query against these Lists looking for the ID.
I pictured a method would be created to query for a file out of the XML file without storing/setting anything, like so:
public Form getFile(Integer id) {
Form ret = new Form();
//Query XML, set to ret...
return ret;
}
I wanted to use value objects, since that's how I'm used to working. So suggested and settled for this in the end:
List<Form> forms = new List<Form>;
So now, we have 2 methods, 1 to populate the 'forms' variable, and then 1 to query it and return the Form... still seems very strange to me.
Also, instead of:
Form tempForm = new Form();
tempForm.id = 1;
tempForm.title = "Foo";
He prefers to do:
Form tempForm = new Form(id, title);
Purely because it's in 1 line and looks tidier. Later down the line though, I don't think using a value object like this is the best way to go.
Maybe I am worrying and thinking about stuff to much as opposed to getting on with development, but any advice on this would be great.
On your second style question:
One of the reasons to use a constructor is that you can then make your Form object immutable as in:
public class Form {
private final String id;
private final String title;
public Form(String id, String title) {
this.id = id; this.title = title;
}
public String getTitle() { return title; }
public String getId() { return id; }
}
This helps avoid concurrency issues.
I'm not sure I understand your question properly, but at the basis, it sounds like a performance question. ie: is it worth reading in an entire XML file, and restructuring it such that it is faster and easier to query, or is it better to scan the xml file every time and query against it. That's a question that only you can answer. As usual, it's the space-speed tradeoff that you have to evaluate.
If your XML file is huge and would require significant amount of memory to cache and you only query against in sporadically, then perhaps your solution is better. If it is small and speed is critical, then caching it is a good idea.
All that being said, there are several different libraries that you can use to speed up the processing in different ways. You can look at using XQuery and/or XPath (see How to read XML using XPath in Java), JAXB, SAX, etc. Each technology has its own advantages and disadvantages.
Hopefully that will give you a little more background that you can discuss with each other.
Interresting question! There are however several questions in one. Let me answer each one of them separately.
Let me first lay down the definition of a value type as found on domaindrivendesign.org
Definition: A Value Object is an object that describes some
characteristic or attribute but carries no concept of identity.
For example a file path is a string, but it also has some restrictions on the format of the string and some operations. Here it would be a good idea to create a value object. Note also that a path carries no notation of identity. That is, two path objects representing the same path would be considered equal.
Now to the actual question, I strongly recommend your way of coding - Creating a class for data that belong together. In your first example id and title are only related by an index into two separate lists.
It's better to use this form
Form tempForm = new Form(id, title);
That way the Form class can be immutable which will give you great readability benefits and also performance gains. Also the fields of the class are encapsulated.
Now to the last thing you thought was strange - Having two methods, one for creating the list and one for querying against it.
Here I would actually create a new class, containing only those two methods instead of having them say in a static class. I would call it a FormCollection. You guys can probably come up with some smarter name since you have more context. Spend at most five minutes figuring out a meaningful name.
You could also refactor your code further to for example take the xml file path or stream as a constructor argument and then have a single method for querying aginst it on id. Like so:
class FormCollection
{
public FormCollection(String xmlFilePath) { ... }
public Form getById(int id) { ... }
}
This is probably a good interface to the rest of your application, since it easy and to the point. Also it's easy to test.
I've the following scenario. My application interacts with the database which contains some static tables. If I have to use that static information in the code level mostly for conditional code, what is the best approach.
For eg: I've a student database, which contains a static table student_type ( indicating hard-working, smart, lazy etc types ). In the code, I need to take action based on the student_type.
So, my code would look like this
studentTypeId = student.getTypeId(); // student constructed from database
switch (studentTypeId)
{
case HARDWORKING_ID :
// do something
case LAZY_ID :
// do something
break;
}
Well, in my code, I would either use constants or an enum to store type ids. But, isn't this kind of replicating things in code since I already have type ids in database. If the type id in database changes I'll have to change the same in my Enum which increases maintenance. Is there a better way to achieve this?
Thanks.
The question to ask is: does the addition of the row in the database imply a change in your java? If yes, go for the enum approach, and don't worry about the duplication. If you're going to have to change code anyway, for instance, to add new cases to your switch, then I usually find it's a good idea to keep things simple.
studentTypeId = student.getTypeId(); // student constructed from database
switch (studentTypeId)
{
case HARDWORKING_ID :
// do something
case LAZY_ID :
// do something
case SMART_ID : // added smart student, very rare corner case :-)
// do something
break;
}
Often in cases where you're storing static data like this you've got other constraints that go with the data, and when you change the data in the database, you have to change the code that uses that data.
If you really really want to reduce the duplication, then you can go for a fully pluggable architecture, as suggested by Dave Newton. This could be implemented as a id -> class name relation for each id. You'd then instantiate the class and all of the logic associated with each id would be contained in that class. This isn't always easy or possible. For your example, it may well be possible, but unless it's done right, this can be complicated.
Also, it doesn't solve all of your problems. You still have to develop the java, test it, and redeploy the new class. So actually, the amount of work you would save may be minimal.
It's often easier to accept the small amount of duplication and just go with the simple solution.
If the student_type table contains only some ID's and perhaps some descriptive text but nothing more as in this small example
ID description
1 'Hard worker'
2 'Lazy snob'
then your only chance is to use the IDs in your code, perhaps giving them proper names using either an enum or some constant interface as you did already. And every change on `student_type' which requires a change in behaviour will require code changes. There is no way out, because the only place where behaviour is formalized and defined is in your code.
IF however the table has formalized content like here
ID description min_ max_ min_ max_ fire_ give_
points points grade grade ASAP kudos
1 'Hard worker' 100 200 B A F T
2 'Lazy snob' 0 50 Z Q T F
3 'Medium' 50 100 P C F F
then the behaviour of your app is not driven by the ID but by the associated data - the data forms a simple rule system. In that case you don't need any constants in your code, because you will implement the rule system like this:
StudentType studentType = student.getStudentType();
if( studentType.isGiveKudos() )
doGiveKudos(student);
if( studentType.isFireAsap() )
doFire(student);
// next student...
This is the way to go if the flexibility is a must.
scratch head Now I don't know if this deviates to much from the question.
There's a bunch of ways this could be implemented. For quick/dirty stuff I'll often store the class name of an implementation in the DB and just instantiate at runtime. Sometimes I'll keep a Groovy implementation in the DB. Sometimes I'll use Spring beans where the factory is stored in the DB. All depends.