Does anyone know how to use data from Oracle database in Java Netbeans?
I have successfully connected the database to Netbeans but I do not know how to actually use this data. All I have done is to create Entity classes from database and JPA Controller classes from Entity Classes which contains methods for CRUD functionality but I do not know how to use them.
Here is an example of a "Insert" button:
Staff s1 = new Staff();
s1.setStaffId(txtId.getText());
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PCR4B");
StaffJpaController ajc = new StaffJpaController(emf);
try {
ajc.create(s1);
} catch (Exception ex) {
Logger.getLogger(StaffGUI.class.getName()).log(Level.SEVERE, null, ex);
}
Is there anything wrong with this part of code? For some reason I get many errors but I am not sure if they come from this part of code or not.
Thanks in advance.
It's too many errors to display them here. The build is successful though.
I was wondering if there is a way to store the data of a table in an ArrayList and then use the ArrayList to make changes to elements and then store them back to the database?
The JPA controller class provides the CRUD functionality but I do not know how to make use of the functions. I do not understand what the EntityManager is.
Related
I'm learning Hibernate and Querydsl on spring boot application.
I'm not sure what i'm doing is right approach or not, This is how i insert many to one entity
// BoardMaster.java
public void addBoards(Boards boards){
this.boards.add(boards);
boards.setBoardMaster(this);
}
// Service.java
#Override
#Transactional
public void save(BoardsRequestDto boardsRequestDto) {
BoardMaster boardMaster = boardMasterService.getOne(boardsRequestDto.getBbsId());
Boards boards = boardsRequestDto.toEntity();
boardMaster.addBoards(boards);
boardMasterRepository.save(boardMaster);
}
Boards is the entity has many to one relation and BoardMaster contains Boards entity as List.
So, first i try to get boardMaster and add boards into boardMaster finally run the save method.
I thought i should use or create update method to add boards into boardMaster but i found article that talks about save() can be use for update as well when i fetch entity from persistence context.
As this article says this method works fine but i'm not sure if this is fine. i feel like it's uncommon since i've never used hibernate before.
And i'm using Querydsl to update entity which feels uncommon as well
#Override
public void modify(BoardMasterRequestDto boardMasterRequestDto, Long bbsId){
queryFactory.update(boardMaster)
.set(boardMaster.bbsName, boardMasterRequestDto.getBbsName())
.set(boardMaster.bbsIntro, boardMasterRequestDto.getBbsIntro())
.set(boardMaster.isPossibleToAttachFiles, boardMasterRequestDto.isPossibleToAttachFiles())
.set(boardMaster.amountOfAttachment, boardMasterRequestDto.getAmountOfAttachment())
.set(boardMaster.availableFileSize, boardMasterRequestDto.getAvailableFileSize())
.set(boardMaster.isPossibleToReply, boardMasterRequestDto.isPossibleToReply())
.set(boardMaster.templateId, boardMasterRequestDto.getTemplateId())
.set(boardMaster.templateName, boardMasterRequestDto.getTemplateName())
.set(boardMaster.useAt, boardMasterRequestDto.isUseAt())
.set(boardMaster.bbsUseFlag, boardMasterRequestDto.getBbsUseFlag())
.set(boardMaster.targetId, boardMasterRequestDto.getTargetId())
.set(boardMaster.countOfComment, boardMasterRequestDto.getCountOfComment())
.set(boardMaster.option, boardMasterRequestDto.getOption())
.set(boardMaster.isPossibleToComment, boardMasterRequestDto.isPossibleToComment())
.set(boardMaster.satisfaction, boardMasterRequestDto.getSatisfaction())
.where(boardMaster.bbsId.eq(bbsId))
.execute();
}
This method works fine as well but i'm sure there is more efficient way to update using Hibernate. Please give me some advice 🙏🏻
If you guys need to more info, please let me know. Thank you!
I'm creating a website for a school project which uses spring for the backend. I'm trying to insert data into the database when new data is saved to a specific table.
I've tried using #HandleAfterCreate and #PrePersist, but neither worked. I'm not very experienced with spring. The teacher told us to use it and now I don't know what do.
#HandleAfterCreate
public void handlePersonBeforeCreate(Person person){
logger.info("Inside Person Before Create....");
Set<Qualifikation> qualifikationen = new HashSet<>();
kompetenzRepository.findAll().forEach(kompetenz -> {
Qualifikation qualifikation = new Qualifikation();
qualifikation.setAusmass(0);
qualifikation.setKompetenz(kompetenz);
qualifikation.setPerson(person);
});
person.setQualifikationen(qualifikationen);
System.out.println(person.getDisplayName());
}
The code should set a person's "Qualifikation" to a default value when the person is inserted (via OAuth login). It should have every "Kompetenz" with a value of 0 by default. Kompetenz has a 1 to n relation to Qualifikation. If you need more information please ask me.
It looks like you're trying to have access to the repository layer of your application inside an entity. This is generally not a good idea, as the entities should only know about the data they hold, not the other application components.
In this particular case it would be wise to use a #Service class with a method that you can call to insert the data into the database. In the method you could then insert any other entities as well. Let your repositories be fields of the service and make them #Autowired.
I think you need to enable JPA auditing . It can be enabled in Spring by add #EnableJpaAuditing to your persistence configuration. This tells Spring to listen JPA entity lifecycle events and call the annotated methods in appropriate places.
Also I think you should make the callback method private if it is meant to be called only when persisted (#PrePersist).
See details here. In this article is also presented entity listeners which might also be a good solution when dealing with multiple entities having a need for same pre-persist functionality.
I think you should create a service class, a repository class and an entity which will be stored through repository. The logic of getting all inner elements and filling it with default value is to be written in service and not a good idea to write in entity class.
If you need any help regarding it, let me know .
Welcome to community!!
I am developing a web application using Spring Boot and Vaadin Framework which suppose to have a feature of processing Microsoft Excel documents, storing data from spreadsheets in custom Java objects, and finally persisting them to database. I am using the Excel Uploader add-on from Vaadin's directory which handles this kind of stuff.
As it is shown in the official examples to this add-on, it perfectly works for populating Vaadin Grid component with data from a spreadsheet and reads it properly with no issues. However, I have problems when I try to store this data in a custom object and call any method of this data type, due to the ClassCastException. This exception is thrown because the program tries to cast objects of the same data types. The thing is that whenever I want to add a SucceededListener using a lambda, the data gathered from an excel document is referenced as a collection of the generic Object type, hence it is needed to cast it to a custom object in order to call specific methods. However, when the program runs and I try to upload an excel document via UI this exception is thrown because that collection of generic Objects becomes a collection of custom data types at some moment.
This is the method where the Excel Uploader is configured:
public void configureExcelUploader() {
ExcelUploader<Person> excelUploader = new ExcelUploader<>(Person.class);
excelUploader.addSuccededListener((event, items)) -> {
List<Person> persons = (List<Person>) items;
persons.callCustomMethod();
});
Upload uploadButton = new Upload("Upload");
uploadButton.setReceiver(excelUploader);
uploadButton.addSucceededListener(excelUploader);
}
I probably miss something or simply do not how to do this kind of operation properly. Is there anyone who knows a proper way of storing results in a custom object in this particular case?
I solved this problem by removing DevTools from maven dependencies and everything worked perfectly.
I have a problem with syncronization of a Database field.
I have a Singleton class for instance EntityManager, I use code like this :
Persistence.createEntityManagerFactory("Myproject_EJB")
I create EntityManager using this singleton from both a WebApplication and from WebService layer and use it for access to persistence.
User can modify this Database field using WebApplication, but data is stored in Database only when request is complete (request can take several seconds). Meanwhile if someone call WebService and ask for same field I have an inconsistent state.
In persistence.xml I have use_second_level_cache and use_query_cache set true, and transaction-type="JTA".
In webApp I use code like this for update data :
EntityManager em = EntityMan.getEMF().createEntityManager();
try {
em.find(Tel.class, tel.getTelId());
em.merge(tel);
em.flush();
} catch (Exception e) {
logger.debug(e.getMessage());
e.printStackTrace();
}
How can I solve please ??
don't use caching for data which is changed frequently, or keep cache time very small ? you can set table level caches
http://www.tutorialspoint.com/hibernate/hibernate_caching.htm
just giving pointers to look not a perfect answer.
I'm a java developer. I'm using spring 4.0.1 and hibernate 4.2.21. I have a class as follow:
#Entity
#Inheritance(...)
public abstract class Feature{
#Id
#GeneratedValue
protected Long id;
...
}
Now I have some many class as follow:
Label.java class:
#Entity
public class Label extends Feature{
protected String str;
...
}
Point.java class:
#Entity
public class Point extends Feature{
protected Integer intg;
...
}
I have more than 20 Entity class that extends from Feature class. Is there any way to add dynamically this classes(such as Label and Point) to the project without writing hard code?
update:
For example, Hibernate get data from a database and then according this data, create models.
Is it possible?
How do I do?
I think its not a good database design that needs to be changed dynamically. It sounds verbose and not consistent. Observe your domain again and try to design a proper entity relationships that wouldnt be changed over run time.
You can try to collect the needed data to build the model and generate a hibernate hbm.xml file for each entity (is xml format and easy to generate with java after reading the data needed as you describe in your update)
After that, you can create programmatically a hibernate configuration object following this http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html#configuration-programmatic
I Think with that approach you can achieve what you want if I understand well your question.
I think you want to generate your entity class at runtime instead of that you have to write your java file and compile it and so on.
If this is your requirement you can use a byte code generator like javassist to generate and annotate your class file at runtime. Then you can persist it to your table using JPA, Hibernate and any other ORM framework.
As I understand you need to develop a tool, collects table names that have one-to-one relationship with Feature table.
My suggestion is like that (tested with Oracle):
1) From your DB, get tables metadata who is referancing your Feature table.
Below will print your Label, Point, etc tables who has foreign key relation to your table.If you want to only generate a subset (irrelevant tables might has this relationship too) may be you put a common foreign key column name and filter out non-related tables with a help of such marking.
Connection connection = jdbcTemplate.getDataSource().getConnection();
DatabaseMetaData metaData = connection.getMetaData();
ResultSet exportedKeys = metaData.getExportedKeys(connection.getCatalog(), "<your_schema_name>", "FEATURE");
while (exportedKeys.next()){
String fkTableName = exportedKeys.getString("FKTABLE_NAME");
String fkColumnName = exportedKeys.getString("FKCOLUMN_NAME");
System.out.println("[fkTableName:" + fkTableName + "], [fkColumnName" + fkColumnName + "]");
}
exportedKeys.close();
2) For the tables you collected above, for each table of our concern, get table metadata for the types and columns.
ResultSet columns = metaData.getColumns(connection.getCatalog(), "<your_schema_name>", "<your_table_name>", null);
while (columns.next()){
String columnName = columns.getString("COLUMN_NAME");
String typeName = columns.getString("TYPE_NAME");
System.out.println("[columnName:" + columnName + "], [typeName" + typeName + "]");
}
columns.close();
3) According to result from 2 generate your Java classes. With fields, getter setters, annotations etc. Then copy them into your source directory. You know the rest :)
Hope this is helpful.
I think you can use Hibernate Reverse Engineering to generate Entity for all the database tables. Please refer this Link. That will explained step by step process to generate entity from database using hibernate reverse engineering.
Do not repeat yourself.
If you really need those classes use an IDE (like eclipse) to generate the classes. Or use generics and inheritance to create only one class that is capable of storing Strings as well as Integers.
But if you do not actually need classes, generate SQL (not JPQL nor HQL) and to store the data in java.util.Map and similar data structures.
Classes are good for:
type safety
combining logic (methods) with data (fields)
describing relationships
In your case you might only need:
store structured data at runtime.
I think you could do this with eclipse, but the classes had to be modified more or less to preserve the inheritance hierarchy.
Righ click on the project name and select Properties
Use project facets if project facets not enabled
Click the JPA if it's not selected, then click OK to close the project properties window.
After enabling JPA in project properties, now right click you eclipse project name again, you should see a new context menu item JPA tools appears. Choose Generate Entities from tables
Select a database connection to let Eclipse get the tables used to generated
class from.
Here is how to setup db in eclipse
It's better to create the entities in a dummy project using the above method and copy the Entity classes to the real project.
Eclipse's Class refactoring may be used to preserve the inheritance hierarchy that you want.
Hope this helps.