Datanucleus autoCreateSchema issue (contradictory error messages) - java

I have a small local H2 database whose content has been create with DataNucleus' JDO implementation. It contains a rawcontainitem table, associated to the following object:
#PersistenceCapable(objectIdClass=RawItemKey.class)
#Index(name="CONTAIN_IDX", members={"prefix", "language", "value"})
public class RawContainItem {
#PrimaryKey
#Column(length=40)
String prefix = "";
#PrimaryKey
#Column(length=2)
String language = "";
#PrimaryKey
#Column(length=Integer.MAX_VALUE)
String value = "";
public RawContainItem(String prefix, String language, String value) {
this.prefix = prefix;
this.language = language;
this.value = value;
}
}
This table currently contains several rows where language="FR". I want to add some more rows with language="EN", but I get strange error messages.
When datanucleus.autoCreateSchema is set to true, I get:
INFO: Managing Persistence of Class : net.dwst.findword.DataNucleus.RawContainItem [Table : RAWCONTAINITEM, InheritanceStrategy : new-table]
23-mars-2012 14:42:49 org.datanucleus.store.rdbms.table.AbstractTable create
INFO: Creating table RAWCONTAINITEM
23-mars-2012 14:42:50 org.datanucleus.store.rdbms.table.AbstractTable executeDdlStatementList
GRAVE: Error thrown executing CREATE TABLE RAWCONTAINITEM
(
"LANGUAGE" VARCHAR(2) NOT NULL,
PREFIX VARCHAR(40) NOT NULL,
"VALUE" VARCHAR(2147483647) NOT NULL,
CONSTRAINT RAWCONTAINITEM_PK PRIMARY KEY ("LANGUAGE",PREFIX,"VALUE")
) : Table "RAWCONTAINITEM" already exists; SQL statement:
CREATE TABLE RAWCONTAINITEM
(
"LANGUAGE" VARCHAR(2) NOT NULL,
PREFIX VARCHAR(40) NOT NULL,
"VALUE" VARCHAR(2147483647) NOT NULL,
CONSTRAINT RAWCONTAINITEM_PK PRIMARY KEY ("LANGUAGE",PREFIX,"VALUE")
) [42101-164]
org.h2.jdbc.JdbcSQLException: Table "RAWCONTAINITEM" already exists;
...
This message is true, the table exists indeed.
When datanucleus.autoCreateSchema is set to false, I get:
Required table missing : "RAWCONTAINITEM" in Catalog "" Schema "".
DataNucleus requires this table to perform its persistence operations.
Either your MetaData is incorrect, or you need to enable "datanucleus.autoCreateTables"
org.datanucleus.store.rdbms.exceptions.MissingTableException:
Required table missing : "RAWCONTAINITEM" in Catalog "" Schema "".
DataNucleus requires this table to perform its persistence operations.
Either your MetaData is incorrect, or you need to enable "datanucleus.autoCreateTables"
...
But the table does exists... What gives?

Related

Persist entity using Java Hibernate API and update if already exists

Have the following table and Java Entity:
CREATE TABLE search_terms (
id int(100) NOT NULL AUTO_INCREMENT,
term varchar(255) NOT NULL DEFAULT '',
last_search_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
search_count int(100) NOT NULL DEFAULT '0',
user_email varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
public class SearchTerms implements Serializable {
private Long id;
private String term;
private Timestamp lastSearchDate;
private int searchCount;
private String userEmail;
Want to persist java objects of the given type into the table above.
Example:
List<String> searchTerms = Arrays.asList("test1", "test2", "test3");
saveSearchParams(searchTerms);
If any of those terms exist in the table, I want to increment searchCount else save as a new row.
Need to use JPA.em().merge(o) etc and not have sql insert/update queries
Added the following constant on the two columns but JPA.em().merge(o) keeps inserting new rows.
#Table(name="search_terms", uniqueConstraints= { #UniqueConstraint(columnNames = {"term", "user_email"})})
saveSearchParams() {
searchTerms.forEach(o -> {
SearchTerms term = new SearchTerms();
term.setSearchCount(1);
term.setTerm((String) o);
term.setUserEmail(email);
jpaApi.em().merge(term);
});
}
Any help on or documentation is appreciated.
Merge can both update and insert, but you should check if the object exists in DB to see if you have to set the counter to one or add one to it, for this you will have to throw a query for each element.
try this:
saveSearchParams() {
searchTerms.forEach(o -> {
//search for example by id or in any other way
SearchTerms term = jpaApi.em().find(SearchTerms.class, o.getId());
if (term == null){
term = new SearchTerms();
term.setSearchCount(1);
}else{
term.setSearchCount(term.getSearchCount()+1);
}
term.setTerm((String) o);
term.setUserEmail(email);
jpaApi.em().merge(term);
});
}

Liquibase not executing for Spring Boot/MySQL app

Spring Boot 1.5.8 and Java 8 here. I've followed all the Spring Boot & Liquibase guides and I can't seem to get Liquibase to work.
Here is a link to a GitHub repo for reproducing the issue exactly, but here's the scoop:
I have the following MySQL v8 database that gets created like so ahead of time (before the app runs):
CREATE DATABASE IF NOT EXISTS troubleshooting_db CHARACTER SET utf8 COLLATE utf8_general_ci;
I have the following src/main/resources/db/changelog files:
db.changelog-master.yaml:
===
databaseChangeLog:
- include:
file: db/changelog/1-setup.sql
1-setup.sql:
===
--liquibase formatted sql
--changeset troubleshooting:1 dbms:mysql
-- LOOKUPS
CREATE TABLE IF NOT EXISTS metric_range_categories (
metric_range_category_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
metric_range_category_ref_id VARCHAR(36) NOT NULL,
metric_range_category_name VARCHAR(250) NOT NULL,
metric_range_category_label VARCHAR(250) NOT NULL,
metric_range_category_description VARCHAR(500) NOT NULL,
CONSTRAINT pk_metric_range_categories PRIMARY KEY (metric_range_category_id),
INDEX idx_metric_range_categories_metric_range_category_ref_id (metric_range_category_ref_id),
INDEX idx_metric_range_categories_metric_range_category_label (metric_range_category_label),
CONSTRAINT uc_metric_range_categories_metric_range_category_ref_id UNIQUE (metric_range_category_ref_id),
CONSTRAINT uc_metric_range_categories_metric_range_category_name UNIQUE (metric_range_category_name),
CONSTRAINT uc_metric_range_categories_metric_range_category_label UNIQUE (metric_range_category_label)
);
-- Lots of other CREATE TABLE statements down here...
And the following JPA-annotated entity:
#Entity
#Table(name = "metric_range_categories")
#AttributeOverrides({
#AttributeOverride(name = "id", column = #Column(name = "metric_range_category_id")),
#AttributeOverride(name = "refId", column = #Column(name = "metric_range_category_ref_id")),
#AttributeOverride(name = "name", column = #Column(name = "metric_range_category_name")),
#AttributeOverride(name = "label", column = #Column(name = "metric_range_category_label")),
#AttributeOverride(name = "description", column = #Column(name = "metric_range_category_description"))
})
public class MetricRangeCategory extends BaseLookup {
public MetricRangeCategory() {
}
public MetricRangeCategory(Long id, String refId, String name, String label, String description) {
super(id, refId, name, label, description);
}
}
At runtime I get the following exception:
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [metric_range_categories]
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:67)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:475)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 29 common frames omitted
So when it starts up, Liquibase does not excute/engage and so Hibernate JPA validation fails because its looking for a table that doesn't exist (because Liquibase never kicked in and did its job!). Any ideas as to where I'm going awry? Why isn't Liquibase kicking in?
There are 2 different problems in the repo:
Wrong location of application.yml. Move it from root to
src/main/resources
Nested property in TroubleshootingConfig.Machine
has null value, because of this bean "authInfo" is not created and context initialization fails. Here is the reference on how Spring Boot Configuration Binding works.

Hibernate Duplicate entry '7090' for key 'PRIMARY'

Im getting following error when the application tries to insert a record row in the db.
SQL Error: 1062, SQLState: 23000
ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '7089' for key 'PRIMARY'
ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
Caused by: java.sql.BatchUpdateException: Duplicate entry '7090' for key 'PRIMARY'
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1269)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:955)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
The definition is
#Id
#Column(name = "CST_CUSTOMER_ID_PK")
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
The part at which the error occurs is :
savedCustomer = customerDao.save(customer);
mtmrsLogger.debug("saved customer id:" + savedCustomer.getId());
/**
* Updating Customer Trans Table
*/
updateCustomerTransForMakerChecker(customer, customerform.getAuditDetails());
/**
* Updating Customer Audit
*/
updateCustomerAuditForMakerChecker(customer, customerform.getAuditDetails());
//status=1;
//Add customer ewallet account
updateCustomerInWalletBalance(customer, customerform.getAuditDetails());
//send sms to customer
smsManager.sendSMSToCUCustomer(customer.getMobileno(), userBean);
}
mtmrsLogger.exiting("CustomerManagerImpl", "addCustomer");
My log shows, program has reached ' Exiting Class: CustomerManagerImpl Method: addCustomer' this part. Im saving the customer ,im setting the same entry in other two tables. The primary key of customer table is foreigh key in other two tables. Im lost please help.
CREATE TABLE `CST_CUSTOMER_INFO` (
`CST_CUSTOMER_ID_PK` bigint(11) NOT NULL AUTO_INCREMENT,
`CST_MOBILE` varchar(30) DEFAULT NULL,
`CST_FIRST_NAME` varchar(50) DEFAULT NULL,
`CST_LAST_NAME` varchar(150) NOT NULL,
`CST_MIDDLE_NAME` varchar(50) DEFAULT NULL,
PRIMARY KEY (`CST_CUSTOMER_ID_PK`)
) ENGINE=InnoDB AUTO_INCREMENT=4103 DEFAULT CHARSET=latin1
Im getting error occassionally in production , but in local its ok..
As table is being modified by more than one application, use of #GenericGenerator(name = "generator", strategy = "increment") will result in ambiguity.
Explanation
Strategy increment : It generates identifiers of type long, short or
int that are unique only when no other process is inserting data into
the same table. It should not be used in the clustered environment.
So you should rethink what strategy is to be used to generate id's. Using sequence or native strategy can resolve your problem.
Replace
`CST_CUSTOMER_ID_PK` bigint(11) NOT NULL AUTO_INCREMENT,
with
`CST_CUSTOMER_ID_PK` bigint(11) NOT NULL,
You are incrementing the id using hibernate/java, no need to make the DBMS increment it also.

Java Swing & Postgres user authentication: Close old connection when new connection opened

I have a Java Swing application that accesses a Postgres database using a simple Singleton Pattern:
public class DatabaseConnection {
private static final String uname = "*******";
private static final String pword = "*******";
private static final String url = "*******************************";
Connection connection;
// load jdbc driver
public DatabaseConnection(){
try{
Class.forName("org.postgresql.Driver");
establishConnection();
} catch (ClassNotFoundException ce) {
System.out.println("Could not load jdbc Driver: ");
ce.printStackTrace();
}
}
public Connection establishConnection() {
// TODO Auto-generated method stub
try{
connection = DriverManager.getConnection(url, uname, pword);
} catch (SQLException e){
System.out.println("Could not connect to database: ");
e.printStackTrace();
}
return connection;
}
}
public class SingletonConnection {
private static DatabaseConnection con;
public SingletonConnection(){}
public static DatabaseConnection instance(){
assert con == null;
con = new DatabaseConnection();
return con;
}
}
This is my user table created by Pgadmin3 (hence the ugly upper cases):
CREATE TABLE "user"
(
id serial NOT NULL,
"userRoleId" integer NOT NULL,
"employeeId" bigint NOT NULL,
"subjectId" bigint NOT NULL,
username text NOT NULL,
cryptpwd text NOT NULL,
"userStatusId" integer NOT NULL,
md5pwd text NOT NULL,
CONSTRAINT pk_user PRIMARY KEY (id),
CONSTRAINT "subjectId" FOREIGN KEY ("subjectId")
REFERENCES subject (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT user_employee_id FOREIGN KEY ("employeeId")
REFERENCES employee (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "user_userRole_id" FOREIGN KEY ("userRoleId")
REFERENCES "userRole" (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "user_userStatus_id" FOREIGN KEY ("userStatusId")
REFERENCES "userStatus" (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "unique_user_userName" UNIQUE (username)
)
Since this application will be run on many machines in a local network, I would like to have only a single connection instance per specific user. That is, if userA logs in from one machine, and userA logs in from another machine moments later, notifications should appear on both machines with the second log in having the option to continue with the connection - in which case, the existing connection is dropped/lost.
I imagine I'd have to add a new column (logged_on boolean) in my user table ... in which case the second log in is handled by finding the value of logged_on and acting appropriately. My question is, how then will I be able to close the first connection? How can I maintain a maximum of one connection - per user - at database level?
Ok, this is what I'm working on. Surprisingly, I was thinking of something along the lines you mentioned Zamezela ... I haven't got it working yet, but I think this should work.
My user table:
CREATE TABLE "user"
(
id serial NOT NULL,
"userRoleId" integer NOT NULL,
"employeeId" bigint NOT NULL,
"subjectId" bigint NOT NULL,
username text NOT NULL,
cryptpwd text NOT NULL,
"userStatusId" integer NOT NULL,
md5pwd text NOT NULL,
"loggedIn" boolean NOT NULL DEFAULT false,
CONSTRAINT pk_user PRIMARY KEY (id),
CONSTRAINT "subjectId" FOREIGN KEY ("subjectId")
REFERENCES subject (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT user_employee_id FOREIGN KEY ("employeeId")
REFERENCES employee (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "user_userRole_id" FOREIGN KEY ("userRoleId")
REFERENCES "userRole" (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "user_userStatus_id" FOREIGN KEY ("userStatusId")
REFERENCES "userStatus" (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "unique_user_userName" UNIQUE (username)
)
I've created a table that records each and every user login. Will help track down on user activity:
CREATE TABLE "userLoginHistory"
(
"userId" integer NOT NULL,
_datetime timestamp without time zone NOT NULL,
hostname text NOT NULL,
"osUsername" text NOT NULL,
id bigserial NOT NULL,
CONSTRAINT "pk_userLoginHistory" PRIMARY KEY (id),
CONSTRAINT "userLoginHistory_user_id" FOREIGN KEY ("userId")
REFERENCES "user" (id) MATCH FULL
ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE
)
I now have three main Stored functions thus far ... may add on to them tomorrow. Getting late.
First one involves requesting for a user login. This returns the user id, role, whether someone is logged on on this user account, and whether this user is active:
create type userLoginRequestReturnType as
(
userId integer, -- user.id
userRoleId integer, -- user.roleId
loggedIn boolean, -- user.loggedIn
userActive boolean -- whether user is active
);
CREATE OR REPLACE FUNCTION "user_login_request"(usernameIn text, passwordIn text)
returns setof userLoginRequestReturnType as
$$
declare
user_Id integer;
user_RoleId integer;
user_StatusId integer;
user_loggedIn boolean;
user_Active boolean;
sql text;
begin
user_Active = false;
select into user_Id, user_RoleId, user_StatusId, user_loggedIn id, "userRoleId", "userStatusId", "loggedIn" from "user" where username = usernameIn and cryptpwd = crypt(passwordIn, cryptpwd);
if (user_id > 0) then -- record found
select into user_Active "user_is_active"(user_StatusId);
else
user_id = 0;
user_RoleId = 0;
user_loggedIn = false;
user_Active = false;
end if;
sql = 'select ' || user_Id || ', ' || user_RoleId || ', ' || user_loggedIn || ', ' || user_Active ||';';
return query execute sql;
end;
$$ language 'plpgsql';
This is passed to the front end. If user_loggedIn is true, and all the other attributes support a successful log in, then the front end will notify the user that there is an existing connection, and whether to continue (disconnecting the existing connection). If it is false, then it just continues (without any prompt) to this function:
CREATE OR REPLACE FUNCTION "user_login_complete"(userIdIN integer, hostnameIN text, osUsernameIN text)
returns bigint as
$$
declare
currentTime timestamp without time zone;
userLoginHistoryId bigint;
begin
-- update user.loggedIn
update "user" set "loggedIn" = true where id = userIdIN;
-- insert into userLoginHistory
currentTime = NOW()::timestamp without time zone;
insert into "userLoginHistory" ("userId", _datetime, hostname, "osUsername") values (userIdIN, currentTime, hostnameIN, osUsernameIN);
select into userLoginHistoryId currval('"userLoginHistory_id_seq"');
return userLoginHistoryId;
end;
$$ language 'plpgsql';
The userLoginHistoryId is stored on the front end, since I'm using an MVC architecture for my Java Swing project, my abstract Model Class will call the following function in its constructor. I have taken your advice and will close the connection in each method.
-- function to check if the current logged in session is the last one recorded in database
-- to be run before each connection to the database as per userId
-- new userLoginHistoryId must be inserted into table userLoginHistory, and the id PK value stored in the front end
--
-- returns: true, if current session is the last session recorded in table userLoginHistory for this user_autosuggest_by_ID
-- : false, if another login session has been recorded.
-- MUST BE EXECUTED BEFORE EACH AND EVERY DATABASE TRANSACTION!!!!!
CREATE OR REPLACE FUNCTION "user_login_session_check"(userIdIN integer, userLoginHistoryIdIN bigint)
returns boolean as
$$
declare
results boolean;
userLoginHistoryId bigint;
begin
results = true;
select into userLoginHistoryId id from "userLoginHistory" where "userId" = userIdIN ORDER BY id DESC LIMIT 1;
if (userLoginHistoryIdIN = userLoginHistoryId) then
results = true;
else
results = false;
end if;
end;
$$ language 'plpgsql';
Will test tomorrow and hopefully it works fine. Please feel free to comment.
Thanks.
#greatkalu your problem is much deeper and very hard achievable, I will suggest you some approach: when user log in you should update two fields(last_access_timestamp, computer_id) and for every access to the database you should update last_access_timestamp. computer_id and last_access_time should be valid maybe 1 hour or less depends of the use of the application. when other person tries to login with same user_id then if now() - 1 hour < last_access_timestamp then that user should not be grant access.
computer_id is generated from application and for every computer should be unique and always generated same computer_id.
I hope this will help

How to get super table information in java?

My database had a lot of parent and child tables.The tables contains the foreign key which has the link with the parent table.I wants to get the information of parent table of the child table using java?How can I achieve that?
For ex,consider the student and mark table,
The student table contains the information like studentID,name.
studentID-Primary key
The marks table contains the markId,studentId,Sub1,sub2,sub3 etc
markId-Primarykey
studentID-Foreignkey refers Student table
My table creation queries are,
CREATE TABLE `Student12` (
`studentId` SMALLINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`studentId`)
)
ENGINE = InnoDB;
CREATE TABLE `Marks` (
`markId` SMALLINT NOT NULL AUTO_INCREMENT,
`subject1` SMALLINT NOT NULL,
`subject2` SMALLINT NOT NULL,
`studentId` SMALLINT NOT NULL,
PRIMARY KEY (`markId`),
CONSTRAINT `FK_Marks_Student` FOREIGN KEY `FK_Marks_Student` (`studentId`)
REFERENCES `Student12` (`studentId`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
ENGINE = InnoDB;
If I give the mark table name as input, how can I get its parent or super table name student and information about student table?Any help should be appreciable.
It totally depends on the way tables are created. Foreign keys are not mandatory to create, they could be a simple column in one table with no explicit relationship to the other table. If you are very sure that the links are created explicitly (the foreign keys are defined) then you could use information_schema. But if there is no foreign key defined (which is true in most of the databases I have seen), then there is no way for you to find the links inside the database. You have to look into the code (if there is any available) and try to find a clue.
The JDBC DatasetMetaData interface provides a couple of methods that may help. (The following text is copied from the javadoc.
ResultSet getExportedKeys(String catalog, String schema, String table)
Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable)
Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).
Of course, these can only work if the relevant columns have been declared as foreign keys in the SQL table DDL.
You can use the DatabaseMetaData to retrieve informations about foreign keyes
and the referenced Tables. Im not sure if it works with all kinds of MySql Tables.
The principle is to use the follwing code (not tested) to retrieve information about the super tables
ResultSet rs = null;
DatabaseMetaData dm = conn.getMetaData( );
// get super tables of table marks
ResultSet rs = dm.getSuperTables( null , null, "marks" );
while( rs.next( ) ) {
System.out.println(String.format("Table Catalog %s", rs.getString("TABLE_CAT") );
System.out.println(String.format("Table Schema %s", rs.getString("TABLE_SCHEM") );
System.out.println(String.format("Table Name %s", rs.getString("TABLE_NAME") );
System.out.println(String.format("Table Name %s", rs.getString("SUPERTABLE_NAME") );
}
You can use thes informations to get additional informations about the referenced table
and the foreigen and referenced primary keys:
ResultSet rs = dm.getCrossReference( null , null , "student" , null , null , "marks" );
System.out.println(String.format("Exported Keys Info Table %s.", "marks"));
while( rs.next( ) ) {
String pkey = rs.getString("PKCOLUMN_NAME");
String ptab = rs.getString("PKTABLE_NAME");
String fkey = rs.getString("FKCOLUMN_NAME");
String ftab = rs.getString("FKTABLE_NAME");
System.out.println("primary key table = " + ptab);
System.out.println("primary key = " + pkey);
System.out.println("foreign key table = " + ftab);
System.out.println("foreign key = " + fkey);
}
And finally you can retrieve the information about the super table by
ResultSet rs = dm.getTables(null,null,"student" ,null);
System.out.println("Table name:");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
System.out.println(table);
}

Categories