List all DB tables - JPA - oracle

I want to list all the tables in my DB using Spring boot and JPA, I have created a DataSource configuration like - configuring-spring-boot-for-oracle and tried -
#Repository
public interface TestRepo extends JpaRepository<Table, Long>{
#Query("SELECT owner, table_name FROM dba_tables")
List<Table> findAllDB();
}
And my Table Entity -
#Entity
public class Table {
String owner;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
And got -
No identifier specified for entity: com.siemens.plm.it.aws.connect.repos.Table
So how do I query for DB tables names?
So far my main -
#SpringBootApplication
public class AwsFileUploadApplication implements CommandLineRunner{
#Autowired
DataSource dataSource;
#Autowired
TestRepo repo;
public static void main(String[] args) {
//https://wwwtest.plm.automation.siemens.com/subsadmin/app/products
SpringApplication.run(AwsFileUploadApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("DATASOURCE = " + dataSource); //some value - ds init sucess
List<Table> findAllDB = repo.findAllDB();
System.out.println(findAllDB);
}
}
When removing #Entity from Table - Not a managed type: class com.siemens.plm.it.aws.connect.repos.Table.

I print all my tables and columns using JDBC:
#Autowired
protected DataSource dataSource;
public void showTables() throws Exception {
DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
ResultSet tables = metaData.getTables(null, null, null, new String[] { "TABLE" });
while (tables.next()) {
String tableName=tables.getString("TABLE_NAME");
System.out.println(tableName);
ResultSet columns = metaData.getColumns(null, null, tableName, "%");
while (columns.next()) {
String columnName=columns.getString("COLUMN_NAME");
System.out.println("\t" + columnName);
}
}
}
If you look at the getTables API you can see how to refine the search of tables.

Related

I am using Spring Jpa Repository to perform all database operations. I don't know how to select a specific value from my table without using any query

My entity class is here:
public class ClientDetails {
public ClientDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
#GeneratedValue
#Column(name="serialno")
public int serialno;
#Column(name="gstnum")
public int GSTnum;
#Column(name="bunk_name")
public String bunk_name;
#Column(name="mobile_num")
public int mobile_num;
#Column(name="password")
public String password;
public int getSerialno() {
return serialno;
}
public void setSerialno(int serialno) {
this.serialno = serialno;
}
public int getGSTnum() {
return GSTnum;
}
public void setGSTnum(int gSTnum) {
GSTnum = gSTnum;
}
public String getBunk_name() {
return bunk_name;
}
public void setBunk_name(String bunk_name) {
this.bunk_name = bunk_name;
}
public int getMobile_num() {
return mobile_num;
}
public void setMobile_num(int mobile_num) {
this.mobile_num = mobile_num;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I want to select gstnum from my table based on my bunk_name.I don't want any native query like i did for gstnum in my jpa repository.
SELECT gstnum from pbm.client_details where bunk_name = 'yoga';
MY JPA REPOSITORY is
public interface ClientDetailsRepository extends JpaRepository<ClientDetails,Integer> {
public static final String gst_num = "SELECT * FROM pbm.client_details;";
//public static final String login_access = "SELECT * FROM clien_details WHERE gstnum pbm.client_details;";
#Query(value = gst_num, nativeQuery = true)
List<ClientDetails> getGstnum();
}
You could use the #Query but Spring Data would result not having too
#Query("SELECT GSTnum FROM ClientDetails where bunk_name = :callMeSomething")
List<ClientDetails> getGstnum(#Param("callMeSomething") String callMeSomething);
How a look here JPA Docs

Spring Boot class cast exception in PostConstruct method

I am running a Spring Boot application with a PostConstruct method to populate a POJO before application initialization. This is to ensure that the database isn't hit by multiple requests to get the POJO content after it starts running.
I'm able to pull the data from Oracle database through Hibernate query and store it in my POJO. The problem arises when I try to access the stored data. The dataset contains a list of objects that contain strings and numbers. Just trying to print the description of the object at the top of the list raises a class cast exception. How should I mitigate this issue?
#Autowired
private TaskDescrBean taskBean;
#PostConstruct
public void loadDescriptions() {
TaskDataLoader taskData = new TaskDataLoader(taskBean.acquireDataSourceParams());
List<TaskDescription> taskList = tdf.getTaskDescription();
taskBean.setTaskDescriptionList(taskList);
System.out.println("Task description size: " + taskBean.getTaskDescriptionList().get(0).getTaskDescription());
}
My POJO class:
#Component
public class TaskDescrBean implements ApplicationContextAware {
#Resource
private Environment environment;
protected List<TaskDescription> taskDescriptionList;
public Properties acquireDataSourceParams() {
Properties dataSource = new Properties();
dataSource.setProperty("hibernate.connection.driver_class", environment.getProperty("spring.datasource.driver-class-name"));
dataSource.setProperty("hibernate.connection.url", environment.getProperty("spring.datasource.url"));
dataSource.setProperty("hibernate.connection.username", environment.getProperty("spring.datasource.username"));
dataSource.setProperty("hibernate.connection.password", environment.getProperty("spring.datasource.password"));
return dataSource;
}
public List<TaskDescription> getTaskDescriptionList() {
return taskDescriptionList;
}
public void setTaskDescriptionList(List<TaskDescription> taskDescriptionList) {
this.taskDescriptionList = taskDescriptionList;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
My DAO class:
public class TaskDataLoader {
private Session session;
private SessionFactory sessionFactory;
public TaskDataLoader(Properties connectionProperties) {
Configuration config = new Configuration().setProperties(connectionProperties);
config.addAnnotatedClass(TaskDescription.class);
sessionFactory = config.buildSessionFactory();
}
#SuppressWarnings("unchecked")
public List<TaskDescription> getTaskDescription() {
List<TaskDescription> taskList = null;
session = sessionFactory.openSession();
try {
String description = "from TaskDescription des";
Query taskDescriptionQuery = session.createQuery(description);
taskList = taskDescriptionQuery.list();
System.out.println("Task description fetched. " + taskList.getClass());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return taskList;
}
TaskDescription Entity:
#Entity
#Table(name="TASK_DESCRIPTION")
#JsonIgnoreProperties
public class TaskDescription implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="TASK_DESCRIPTION_ID")
private Long taskDescriptionId;
#Column(name="TASK_DESCRIPTION")
private String taskDescription;
public Long getTaskDescriptionId() {
return taskDescriptionId;
}
public void setTaskDescriptionId(Long taskDescriptionId) {
this.taskDescriptionId = taskDescriptionId;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
}
StackTrace
Instead of sending the List in the return statement, I transformed it into a JSON object and sent its String representation which I mapped back to the Object after transforming it using mapper.readValue()

Spring boot H2 database application

I have created a sample project with following code. Even if i am not providing table create statement in the data.sql, it is creating the table. how to stop that. Sample code is present below
Can you please let me know what I am doing wrong? I have removed the import statements below as the post was not allowing to put so much code here.
package com.example.demo;
// Model class
#Entity
#Table(name="reservation")
public class Reservation {
#Id
private Long id;
#Column(name="user_id")
private Long userId;
#Column(name="party_size")
private int partySize;
#Column(name="restaurant_id")
private Long restaurantId;
#Column(name="date")
private LocalDateTime dt;
public Reservation() {}
public Reservation(Long id, Long userId, int partySize) {
this.id = id;
this.userId = userId;
this.partySize = partySize;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public int getPartySize() {
return partySize;
}
public void setPartySize(int partySize) {
this.partySize = partySize;
}
public Long getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Long restaurantId) {
this.restaurantId = restaurantId;
}
public LocalDateTime getDt() {
return dt;
}
public void setDt(LocalDateTime dt) {
this.dt = dt;
}
}
package com.example.demo;
#SpringBootApplication
public class ReservationApp {
public static void main(String[] args) {
SpringApplication.run(ReservationApp.class, args);
}
}
package com.example.demo;
#RestController
#RequestMapping("/v1")
public class ReservationController {
#Autowired
private ReservationService reservationService;
// ------------ Retrieve all reservations ------------
#RequestMapping(value = "/reservations", method = RequestMethod.GET)
public List getAllReservations() {
return reservationService.getAllReservations();
}
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface ReservationRepository extends CrudRepository<Reservation,String> {
}
package com.example.demo;
#Service
public class ReservationService {
#Autowired
private ReservationRepository reservationRepository;
// Retrieve all rows from table and populate list with objects
public List getAllReservations() {
List reservations = new ArrayList<>();
reservationRepository.findAll().forEach(reservations::add);
return reservations;
}
}
try to remove the spring boot hibernate configuration
spring.jpa.hibernate.ddl-auto = update
Which is able of creating/updating the database schema from entities
To disable automatic DDL generation, set the following property to false in application.properties:
spring.jpa.generate-ddl = false
For more information and fine-grained control, please see the documentation.
Set the ddl generation to none in the application.properties:
spring.jpa.hibernate.ddl-auto=none

JPA Callback not being called

I am new to hibernate. I want to know if any crud operation happens so I decided to use jpa callback annotations. The problem is any of those #PrePersist #PostPersist #PreRemove #PostRemove not being called when I run the project and use UI components to perform delete & add operations. I use primefaces datatable so delete operation bounded to a ManagedBean -> MessageService ->MessageDAO. IF I only execute the main file to test it it works perfectly
MessageDAO:
#Component
public class MessageDAO {
#PersistenceContext
private EntityManager em;
#Transactional
public void register(Message message) {
em.persist(message);
}
#Transactional
public void delete(Integer id) {
Message m = em.find(Message.class, id);
em.remove(em.merge(m));
}
}
MessageListener
public class MessageListener {
#PrePersist
public void prePersist(Message o) {
System.out.println("Pre-Persistiting operation: " );
}
#PostPersist
public void postPersist(Message o) {
System.out.println("Post-Persist operation: " );
}
#PreRemove
public void preRemove(Message o) {
System.out.println("Pre-Removing operation: " );
}
#PostRemove
public void postRemove(Message o) {
System.out.println("Post-Remove operation: " );
}
#PreUpdate
public void preUpdate(Message o) {
System.out.println("Pre-Updating operation: ");
}
#PostUpdate
public void postUpdate(Message o) {
System.out.println("Post-Update operation: " );
}
}
Message
#EntityListeners(MessageListener.class)
#Entity
#Table(name = "messages")
public class Message implements Serializable {
private Integer messageId;
private String subject;
private String content;
public Message(){}
public Message(Integer messageId, String subject, String content) {
this.messageId = messageId;
this.subject = subject;
this.content = content;
}
#Id
#GeneratedValue
#Column(name = "MESSAGE_ID")
public Integer getMessageId() {
return messageId;
}
//getter setter
#PrePersist
public void prePersist() {
System.out.println("OLDUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU!!!!!!!!!!!!");
}
}
As per the JPA spec, JPA callbacks/listeners are not called when using JPQL BULK DELETE. They are only called when using the JPA API (em.remove). Similarly the cache and managed entity objects do not reflect such a JPQL BULK DELETE call.
change Your code by following example hope it will work
#Transactional
public void delete(Long id) {
Message m = em.find(Message.class, id);
em.remove(em.merge(m));
}
}

Spark insert to Hbase

I have a pojo class of emp like below:
I am able to read streaming data and I want to insert data to Hbase
#JsonInclude(Include.NON_NULL)
public class empData implements Serializable {
private String id;
private String name;
#Override
public String toString() {
return "id=" + id + ", name="+ name ;
}
public String id() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Below is spark code:
empRecords.foreachRDD(new Function<JavaRDD<empData>, Void>() {
private static final long serialVersionUID = 1L;
#Override
public Void call(JavaRDD<empData> empDataEvent)throws Exception {
Configuration conf = HBaseConfiguration.create();
Configuration config = null;
config = HBaseConfiguration.create();
config.set("hbase.zookeeper.quorum", "**********);
HBaseAdmin.checkHBaseAvailable(config);
config.set(TableInputFormat.INPUT_TABLE, "tableName");
Job newAPIJobConfiguration1 = Job.getInstance(config);
newAPIJobConfiguration1.getConfiguration().set(TableOutputFormat.OUTPUT_TABLE, "empHbase");
newAPIJobConfiguration1.setOutputFormatClass(org.apache.hadoop.hbase.mapreduce.TableOutputFormat.class);
JavaPairRDD<ImmutableBytesWritable, Put> inesrts = empData.mapToPair(new PairFunction<Row, ImmutableBytesWritable, Put>() {
public Tuple2<ImmutableBytesWritable, Put> call(Row row) throws Exception
{
Put put = new Put(Bytes.toBytes(row.getString(0)));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("id"),Bytes.toBytes(row.getString(1)));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("name"),Bytes.toBytes(row.getString(2)));
return new Tuple2<ImmutableBytesWritable, Put>(new ImmutableBytesWritable(), put);
}
});
inserts.saveAsNewAPIHadoopDataset(newAPIJobConfiguration1.getConfiguration());
}
});
jssc.start();
jssc.awaitTermination();
}
The problem in the code is this step:
JavaPairRDD<ImmutableBytesWritable, Put> inesrts =empDataEvent.mapToPair(new PairFunction<Row, ImmutableBytesWritable, Put>()
How to use empDataEvent and how to insert..
How do I insert as mapToPair empDataEvent class object so that I can insert into Hbase.
Any help appreciated..
Aman,
In your code you have refer "Row", can you please elaborate where it is coming from? because there is no reference for it.
See updated code below, use class name "empData" instead of "Row" object.
JavaPairRDD<ImmutableBytesWritable, Put> inesrts = empData.mapToPair(new PairFunction<empData, ImmutableBytesWritable, Put>() {
public Tuple2<ImmutableBytesWritable, Put> call(empData row) throws Exception
{
Put put = new Put(Bytes.toBytes(row.id));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("id"),Bytes.toBytes(row.id));
put.add(Bytes.toBytes("empA"),Bytes.toBytes("name"),Bytes.toBytes(row.getName));
return new Tuple2<ImmutableBytesWritable, Put>(new ImmutableBytesWritable(), put);
}
});

Resources