Hi I want to insert into this kind of column family row with composite key:
CREATE TABLE my_items (
user_id uuid,
item_id uuid,
description varchar,
PRIMARY KEY (user_id, item_id));
So I try this:
StringSerializer stringSerializer = StringSerializer.get();
UUIDSerializer uuidSerializer = UUIDSerializer.get();
CompositeSerializer compositeSerializer = CompositeSerializer.get();
HColumn<String, UUID> hColumnObj_userID = HFactory.createColumn("user_id", userID, stringSerializer, uuidSerializer);
HColumn<String, UUID> hColumnObj_itemID= HFactory.createColumn("item_id", itemID, stringSerializer, uuidSerializer);
Mutator<Composite> mutator = HFactory.createMutator(
repository.getKeyspace(),
compositeSerializer);
Composite colKey = new Composite();
colKey.addComponent(userID, uuidSerializer);
colKey.addComponent(itemID, uuidSerializer);
mutator.addInsertion(colKey,
"my_items", hColumnObj_userID);
mutator.addInsertion(colKey,
"my_items", hColumnObj_itemID);
mutator.execute();
What's wrong with code above? I keep getting this error: "InvalidRequestException(why:UUIDs must be exactly 16 bytes)". And how can I insert data into column family that I describe above.
Cheers
It looks like Hector was expecting a Composite containing a UUID and a String and found only a string.
Before writing the Hector code you have to translate the create DDL into the actual storage pattern CQL uses. In this case, even though you have two primary keys, only the first, user_id, is used as the row key. That's always the case. Any other primary keys (item_id in this case) are used to form composite column names for every column except the first primary key. That means that when using Hector for your my_items column family you'll have to write two columns, one for item_ID and one for description.
The column name for the item_id value is a composite consisting of the values of primary keys 2...n (item_id in this example) and a constant string name of the value ("item_id").
The column name for the description value is also a composite of the item_id value and the name of the value ("description").
If you wrote 3 CQL table rows, each with the same user_id but having different item_id values then you'd end up with a single column family row whose row key is the common user_id value and which has 6 columns, an item_id column and a description column for each of the 3 CQL table rows.
The code should look like this:
import java.util.UUID;
import me.prettyprint.cassandra.serializers.CompositeSerializer;
import me.prettyprint.cassandra.serializers.IntegerSerializer;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.serializers.UUIDSerializer;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.Composite;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.beans.AbstractComposite.ComponentEquality;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
// put this here to make it compile cleanly
Keyspace keyspace = null;
UUID userID = null;
UUID itemID = null;
String description = null;
// Row key is user_id of type UUID
Mutator<UUID> mutator = HFactory.createMutator(
keyspace,
UUIDSerializer.get());
// write column for itemID.
// Column name is composite of itemID value and constant "item_id"
// Row key is value of userID
Composite itemIdColumnName = new Composite();
itemIdColumnName.addComponent(itemID , UUIDSerializer.get());
itemIdColumnName.addComponent("item_id" , StringSerializer.get());
// HFactory.createColumn takes args: column name, column value, serializer for column name, serializer for column value
HColumn<Composite, UUID> hColumnObj_itemID = HFactory.createColumn(itemIdColumnName, userID, new CompositeSerializer(), UUIDSerializer.get());
mutator.addInsertion(userID, "my_items", hColumnObj_itemID);
// write column for description.
// Column name is composite of itemID value and constant "description"
// Row key is value of userID
Composite descriptionColumnName = new Composite();
itemIdColumnName.addComponent(itemID , UUIDSerializer.get());
itemIdColumnName.addComponent("description" , StringSerializer.get());
HColumn<Composite, String> hColumnObj_description = HFactory.createColumn(descriptionColumnName, description , new CompositeSerializer(), StringSerializer.get());
mutator.addInsertion(userID, "my_items", hColumnObj_description);
mutator.execute();
Related
I´m using Postgres and java to write files out of a .csv into a db. In my CREATE TABLE stmnts, I have a table which stores two keys. These I want to insert. I now have a subquery but i always get a null value for the ckey, so the syntax must be wrong. The INSERT does not work. ERROR: null value in column "ckey" of relation "gamesin" violates not-null constraint. The other value I get out of a list I created. I´m using a prepared statement. Help appreciated!
CREATE TABLE Games(
Year INT PRIMARY KEY,
Name VARCHAR(32) NOT NULL,
StartDate Date NOT NULL,
EndDate Date NOT NULL
);
CREATE TABLE Cities(
CKey SERIAL PRIMARY KEY,
Name VARCHAR(128) UNIQUE NOT NULL,
Noc CHAR(3) REFERENCES Countries NOT NULL
);
CREATE TABLE GamesIn(
Year INT REFERENCES Games,
CKey INT REFERENCES Cities,
PRIMARY KEY(Year, CKey)
);
String sql = "INSERT INTO gamesin (year, ckey) VALUES (?, (SELECT ckey from cities WHERE cities.name = '\" + name + \"'))";
I am new to Cassandra and use Cassandra 3.10 and have table like
create table db1.table1 (id text, trip_id text, event_time timestamp, mileage double, primary key(id, event_time));
create table db1.table2 (id text, trip_id text, start_time timestamp, mileage double, primary key(id, start_time));
I need to transfer data from table1 to table2 aggregated by trip_id and sum on mileage and update data in table2
I have written a trigger function to get column name and value
public Collection<Mutation> augment(Partition partition) {
HashMap map = new HashMap();
CFMetaData cfm = partition.metadata();
String tableName = cfm.cfName;
try {
UnfilteredRowIterator it = partition.unfilteredIterator();
while (it.hasNext()) {
Unfiltered un = it.next();
Clustering clt = (Clustering) un.clustering();
Iterator<Cell> cells = partition.getRow(clt).cells().iterator();
while(cells.hasNext()){
Cell cell = cells.next();
map.put(cell.column().name.toString(), cell.value().array());
...
}
}
} catch (Exception e) {
}
...
}
But how can I get Primary key and the value of Primary key? If those are not gettable, how can I use trigger function to do the job?
Yes, It is possible to get primary key and value
To get partition keys column and value use :
List<ColumnDefinition> partitionKeyColumns = cfm.partitionKeyColumns();
ByteBuffer partitionKeyValues = partition.partitionKey().getKey();
To get clustering keys column and value :
List<ColumnDefinition> clusteringKeyColumns = cfm.clusteringColumns();
ByteBuffer[] clusteringKeyValues = clt.getRawValues();
My javaFx application has many tables with editable table cells to populate data from sql database.I also want to make changes in database after data editing through table cells.According to this toturial "https://docs.oracle.com/javafx/2/ui_controls/table-view.htm"
I have created my editable table cell with the following code.
item_price_col.setCellValueFactory(
new PropertyValueFactory("price")
);
item_price_col.setCellFactory(TextFieldTableCell.forTableColumn());
item_price_col.setOnEditCommit(
new EventHandler<CellEditEvent<Item, String>>() {
#Override
public void handle(CellEditEvent<Item,String> t) {
String old_price=t.getOldValue();
((Item) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setPrice(t.getNewValue());
String new_price=t.getNewValue();
System.out.println("Old Price:"+old_price);
System.out.println("New Price:"+new_price);
}
}
);
But it doesn't make any changes in database after editing.So,I think have to write update Query inside of that handle method.But I can only know old value and new value. I can't make query statement like that "update item set price=new_price where price=old_price".If I update a single price of a item to new value,every items in my item table that have the same price with my edited item will make changes to new price value.Are there any ways to solve this problem?
Here is my item table structure.
item | CREATE TABLE `item` (
`code` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`price` varchar(50) NOT NULL,
`whole_sale_price` varchar(50) NOT NULL,
`orginal_price` varchar(50) DEFAULT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
Keep an id field to your item as it is given in the database.
If you have not primary or unique key in the database probably you made some architectural mistake. Anyway there is a row id specified in some database servers.
private int id; // id field for item object.
While updating include id as condition.
update sometable set price = item.getPrice() where id = item.getId();
I know sql is not well written but I hope you'll get it
And you don't have to show value of id field in your table grid.
This technique is used in most systems
EDITED 2015.12.18
You have code column in the table. Retrieve by jdbc into your item object's id field.
There is an example
http://www.tutorialspoint.com/jdbc/jdbc-update-records.htm
I am writing java class to get all connection database objects(tables). I have used
rs = meta.getExportedKeys(conn.getCatalog(), null, "account_adjustment");
while (rs.next()) {
String fkTableName = rs.getString("FKTABLE_NAME");
String fkColumnName = rs.getString("FKCOLUMN_NAME");
int fkSequence = rs.getInt("KEY_SEQ");
}
which is giving parent table and it's column linked this asked table(account_adjustment)
and also I tried
rs1 = meta.getImportedKeys(conn.getCatalog(), null, "account_adjustment");
while (rs1.next()) {
String fkTableName = rs1.getString("FKTABLE_NAME");
String fkColumnName = rs1.getString("FKCOLUMN_NAME");
int fkSequence = rs1.getInt("KEY_SEQ");
}
which is giving current table(account_adjustment) table and it's foreign key column name
but I want table name with which this foreign key is linked
I have got solution bt in other way not using java,, instead of getting values using java i executed query to 'information_schema' (which is there by default in MySQL) database and 'REFERENTIAL_CONSTRAINTS' table to get all reference of respective tables of required database
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);
}