I am trying to implement Ignite 3rd party persistence with SQL Server. I used the Web Console to generate the java model and I am able to execute the generated utility and configuration files without any issue (LoadCaches or ServerNodeCodeStartup, with config from ServerConfigurationFactory) -- the cache load call executes without any problem.
public TestPersistentStore() throws Exception {
try (Ignite ignite = Ignition.start(ServerConfigurationFactory.createConfiguration())) {
// Auto-close cache at the end of the example.
try (IgniteCache<Integer, Customer> cache = ignite.cache("CustomerCache")) {
// Make initial cache loading from persistent store. This is a
// distributed operation and will call CacheStore.loadCache(...)
// method on all nodes in topology.
loadCache(cache);
// Start transaction and execute several cache operations with
// read/write-through to persistent store.
executeTransaction(cache);
} catch (Exception e) {
e.printStackTrace();
} finally {
// Distributed cache could be removed from cluster only by #destroyCache() call.
ignite.destroyCache("CustomerCache");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Content of executeTransaction:
private static void executeTransaction(IgniteCache<Integer, Customer> cache) {
int id = 1;
try (Transaction tx = Ignition.ignite("acmecorp").transactions().txStart()) {
Customer val = cache.get(id);
System.out.println("Read value: " + val);
val = cache.getAndPut(id, new Customer(id, "Isaac", "Newton", "Ixelles"));
System.out.println("Overwrote old value: " + val);
val = cache.get(id);
System.out.println("Read value: " + val);
tx.commit();
}
System.out.println("Read value after commit: " + cache.get(id));
}
(many of these lines of code were copied from CacheJdbcStoreExample)
Result of execution:
[22:53:35] Topology snapshot [ver=1, servers=1, clients=0, CPUs=4, heap=3.5GB]
>>> Loaded 10 keys with backups in 450ms.
Read value: Customer [firstName=Isaac, lastName=Newton, address=Ixelles]
Overwrote old value: Customer [firstName=Isaac, lastName=Newton, address=Ixelles]
Read value: Customer [firstName=Isaac, lastName=Newton, address=Ixelles]
Read value after commit: Customer [firstName=Isaac, lastName=Newton, address=Ixelles]
Read value skipping store (expecting null): null
Read value with store lookup (expecting NOT null): Customer [firstName=Isaac, lastName=Newton, address=Ixelles]
Read value skipping store (expecting NOT null): Customer [firstName=Isaac, lastName=Newton, address=Ixelles]
[22:53:36] Ignite node stopped OK [name=acmecorp, uptime=00:00:00:638]
So this works for the Customer table/cache. I want to use the same code but use another table/cache (Item), as follows:
TestPersistentStore2
public TestPersistentStore2() throws Exception {
try (Ignite ignite = Ignition.start(ServerConfigurationFactory.createConfiguration())) {
// Auto-close cache at the end of the example.
try (IgniteCache<Integer, Item> cache = ignite.cache("ItemCache")) {
// Make initial cache loading from persistent store. This is a
// distributed operation and will call CacheStore.loadCache(...)
// method on all nodes in topology.
loadCache(cache);
// Start transaction and execute several cache operations with
// read/write-through to persistent store.
executeTransaction(cache);
} catch (Exception e) {
System.out.println("sumthin happened");
e.printStackTrace();
} finally {
// Distributed cache could be removed from cluster only by #destroyCache() call.
ignite.destroyCache("ItemCache");
}
} catch (Exception e) {
e.printStackTrace();
}
}
TestPersistentStore2#executeTransaction
private static void executeTransaction(IgniteCache<Integer, Item> cache) {
int id = 1;
try (Transaction tx = Ignition.ignite("acmecorp").transactions().txStart()) {
Item val = cache.get(id);
System.out.println("Read value: " + val);
val = cache.getAndPut(id, new Item(id, "n", "b", "t", "m", "d"));
System.out.println("Overwrote old value: " + val);
val = cache.get(id);
System.out.println("Read value: " + val);
tx.commit();
}
System.out.println("Read value after commit: " + cache.get(id));
// Clear entry from memory, but keep it in store.
cache.clear(id);
// Operations on this cache will not affect store.
IgniteCache<Integer, Item> cacheSkipStore = cache.withSkipStore();
System.out.println("Read value skipping store (expecting null): " + cacheSkipStore.get(id));
System.out.println("Read value with store lookup (expecting NOT null): " + cache.get(id));
// Expecting not null, since entry should be in memory since last call.
System.out.println("Read value skipping store (expecting NOT null): " + cacheSkipStore.get(id));
}
However I get the following exception in the cache.get(id) call of executeTransaction:
>>> Loaded 72 keys with backups in 648ms.
javax.cache.CacheException: class org.apache.ignite.IgniteCheckedException: Unknown pair [platformId=0, typeId=123254525]
at org.apache.ignite.internal.processors.cache.GridCacheUtils.convertToCacheException(GridCacheUtils.java:1312)
at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.cacheException(IgniteCacheProxy.java:2630)
at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.get(IgniteCacheProxy.java:1188)
at infoh415.project.test.TestPersistentStore2.executeTransaction(TestPersistentStore2.java:98)
at infoh415.project.test.TestPersistentStore2.<init>(TestPersistentStore2.java:69)
at infoh415.project.test.TestPersistentStore2.main(TestPersistentStore2.java:130)
Caused by: class org.apache.ignite.IgniteCheckedException: Unknown pair [platformId=0, typeId=123254525]
at org.apache.ignite.internal.util.IgniteUtils.cast(IgniteUtils.java:7229)
at org.apache.ignite.internal.util.future.GridFutureAdapter.resolve(GridFutureAdapter.java:258)
at org.apache.ignite.internal.util.future.GridFutureAdapter.get0(GridFutureAdapter.java:170)
at org.apache.ignite.internal.util.future.GridFutureAdapter.get(GridFutureAdapter.java:139)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter.get0(GridCacheAdapter.java:4499)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter.get(GridCacheAdapter.java:4480)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter.get(GridCacheAdapter.java:1324)
at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.get(IgniteCacheProxy.java:1181)
... 3 more
Caused by: java.lang.ClassNotFoundException: Unknown pair [platformId=0, typeId=123254525]
at org.apache.ignite.internal.MarshallerContextImpl.getClassName(MarshallerContextImpl.java:392)
at org.apache.ignite.internal.MarshallerContextImpl.getClass(MarshallerContextImpl.java:342)
at org.apache.ignite.internal.binary.BinaryContext.descriptorForTypeId(BinaryContext.java:686)
at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize0(BinaryReaderExImpl.java:1755)
at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize(BinaryReaderExImpl.java:1714)
at org.apache.ignite.internal.binary.BinaryObjectImpl.deserializeValue(BinaryObjectImpl.java:797)
at org.apache.ignite.internal.binary.BinaryObjectImpl.value(BinaryObjectImpl.java:143)
at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinary(CacheObjectUtils.java:161)
at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinaryIfNeeded(CacheObjectUtils.java:41)
at org.apache.ignite.internal.processors.cache.CacheObjectContext.unwrapBinaryIfNeeded(CacheObjectContext.java:125)
at org.apache.ignite.internal.processors.cache.GridCacheContext.unwrapBinaryIfNeeded(GridCacheContext.java:1734)
at org.apache.ignite.internal.processors.cache.GridCacheContext.unwrapBinaryIfNeeded(GridCacheContext.java:1722)
at org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedSingleGetFuture.setResult(GridPartitionedSingleGetFuture.java:645)
at org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedSingleGetFuture.localGet(GridPartitionedSingleGetFuture.java:438)
at org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedSingleGetFuture.mapKeyToNode(GridPartitionedSingleGetFuture.java:324)
at org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedSingleGetFuture.map(GridPartitionedSingleGetFuture.java:212)
at org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedSingleGetFuture.init(GridPartitionedSingleGetFuture.java:204)
at org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicCache.getAsync0(GridDhtAtomicCache.java:1445)
at org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicCache.access$1600(GridDhtAtomicCache.java:129)
at org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicCache$16.apply(GridDhtAtomicCache.java:513)
at org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicCache$16.apply(GridDhtAtomicCache.java:511)
at org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicCache.asyncOp(GridDhtAtomicCache.java:806)
at org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicCache.getAsync(GridDhtAtomicCache.java:511)
... 7 more
Disconnected from the target VM, address: '127.0.0.1:49513', transport: 'socket'
I double checked the differences between the CacheConfiguration for CustomerCache and for ItemCache, there is nothing unexpected (the only differnces are in the table and field names). I also compared the model classes, again they are similar.
Attaching here the config of CustomerCache
/**
* Create configuration for cache "CustomerCache".
*
* #return Configured cache.
* #throws Exception if failed to create cache configuration.
**/
public static CacheConfiguration cacheCustomerCache() throws Exception {
CacheConfiguration ccfg = new CacheConfiguration();
ccfg.setName("CustomerCache");
ccfg.setCacheMode(CacheMode.PARTITIONED);
ccfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
CacheJdbcPojoStoreFactory cacheStoreFactory = new CacheJdbcPojoStoreFactory();
cacheStoreFactory.setDataSourceFactory(new Factory<DataSource>() {
/** {#inheritDoc} **/
#Override public DataSource create() {
return DataSources.INSTANCE_dsSQLServer_Acmecorp;
};
});
cacheStoreFactory.setDialect(new SQLServerDialect());
cacheStoreFactory.setTypes(jdbcTypeCustomer(ccfg.getName()));
ccfg.setCacheStoreFactory(cacheStoreFactory);
ccfg.setReadThrough(true);
ccfg.setWriteThrough(true);
ArrayList<QueryEntity> qryEntities = new ArrayList<>();
QueryEntity qryEntity = new QueryEntity();
qryEntity.setKeyType("java.lang.Integer");
qryEntity.setValueType("infoh415.project.model.Customer");
qryEntity.setKeyFieldName("customerId");
HashSet<String> keyFields = new HashSet<>();
keyFields.add("customerId");
qryEntity.setKeyFields(keyFields);
LinkedHashMap<String, String> fields = new LinkedHashMap<>();
fields.put("firstName", "java.lang.String");
fields.put("lastName", "java.lang.String");
fields.put("address", "java.lang.String");
fields.put("customerId", "java.lang.Integer");
qryEntity.setFields(fields);
HashMap<String, String> aliases = new HashMap<>();
aliases.put("customerId", "customer_id");
aliases.put("firstName", "first_name");
aliases.put("lastName", "last_name");
qryEntity.setAliases(aliases);
qryEntities.add(qryEntity);
ccfg.setQueryEntities(qryEntities);
return ccfg;
}
/**
* Create JDBC type for "jdbcTypeCustomer".
*
* #param cacheName Cache name.
* #return Configured JDBC type.
**/
private static JdbcType jdbcTypeCustomer(String cacheName) {
JdbcType type = new JdbcType();
type.setCacheName(cacheName);
type.setKeyType(Integer.class);
type.setValueType("infoh415.project.model.Customer");
type.setDatabaseSchema("dbo");
type.setDatabaseTable("Customer");
type.setKeyFields(new JdbcTypeField(Types.INTEGER, "customer_id", int.class, "customerId"));
type.setValueFields(
new JdbcTypeField(Types.VARCHAR, "first_name", String.class, "firstName"),
new JdbcTypeField(Types.VARCHAR, "last_name", String.class, "lastName"),
new JdbcTypeField(Types.VARCHAR, "address", String.class, "address")
);
return type;
}
vs. config of ItemCache
/**
* Create configuration for cache "ItemCache".
*
* #return Configured cache.
* #throws Exception if failed to create cache configuration.
**/
public static CacheConfiguration cacheItemCache() throws Exception {
CacheConfiguration ccfg = new CacheConfiguration();
ccfg.setName("ItemCache");
ccfg.setCacheMode(CacheMode.PARTITIONED);
ccfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
CacheJdbcPojoStoreFactory cacheStoreFactory = new CacheJdbcPojoStoreFactory();
cacheStoreFactory.setDataSourceFactory(new Factory<DataSource>() {
/** {#inheritDoc} **/
#Override public DataSource create() {
return DataSources.INSTANCE_dsSQLServer_Acmecorp;
};
});
cacheStoreFactory.setDialect(new SQLServerDialect());
cacheStoreFactory.setTypes(jdbcTypeItem(ccfg.getName()));
ccfg.setCacheStoreFactory(cacheStoreFactory);
ccfg.setReadThrough(true);
ccfg.setWriteThrough(true);
ArrayList<QueryEntity> qryEntities = new ArrayList<>();
QueryEntity qryEntity = new QueryEntity();
qryEntity.setKeyType("java.lang.Integer");
qryEntity.setValueType("infoh415.project.model.Item");
qryEntity.setKeyFieldName("itemId");
HashSet<String> keyFields = new HashSet<>();
keyFields.add("itemId");
qryEntity.setKeyFields(keyFields);
LinkedHashMap<String, String> fields = new LinkedHashMap<>();
fields.put("name", "java.lang.String");
fields.put("brand", "java.lang.String");
fields.put("type", "java.lang.String");
fields.put("manufacturer", "java.lang.String");
fields.put("description", "java.lang.String");
fields.put("itemId", "java.lang.Integer");
qryEntity.setFields(fields);
HashMap<String, String> aliases = new HashMap<>();
aliases.put("itemId", "item_id");
qryEntity.setAliases(aliases);
qryEntities.add(qryEntity);
ccfg.setQueryEntities(qryEntities);
return ccfg;
}
/**
* Create JDBC type for "jdbcTypeItem".
*
* #param cacheName Cache name.
* #return Configured JDBC type.
**/
private static JdbcType jdbcTypeItem(String cacheName) {
JdbcType type = new JdbcType();
type.setCacheName(cacheName);
type.setKeyType(Integer.class);
type.setValueType("infoh415.project.model.Item");
type.setDatabaseSchema("dbo");
type.setDatabaseTable("Item");
type.setKeyFields(new JdbcTypeField(Types.INTEGER, "item_id", int.class, "itemId"));
type.setValueFields(
new JdbcTypeField(Types.VARCHAR, "name", String.class, "name"),
new JdbcTypeField(Types.VARCHAR, "brand", String.class, "brand"),
new JdbcTypeField(Types.VARCHAR, "type", String.class, "type"),
new JdbcTypeField(Types.VARCHAR, "manufacturer", String.class, "manufacturer"),
new JdbcTypeField(Types.VARCHAR, "description", String.class, "description")
);
return type;
}
Model class of Customer
package infoh415.project.model;
import java.io.Serializable;
/**
* Customer definition.
*
* This file was generated by Ignite Web Console (11/26/2017, 10:52)
**/
public class Customer implements Serializable {
/** */
private static final long serialVersionUID = 0L;
private int customerId;
/** Value for firstName. */
private String firstName;
/** Value for lastName. */
private String lastName;
/** Value for address. */
private String address;
public Customer(String firstName, String lastName, String address) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public Customer(int customerId, String firstName, String lastName, String address) {
this.customerId = customerId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
/**
* Gets firstName
*
* #return Value for firstName.
**/
public String getFirstName() {
return firstName;
}
/**
* Sets firstName
*
* #param firstName New value for firstName.
**/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Gets lastName
*
* #return Value for lastName.
**/
public String getLastName() {
return lastName;
}
/**
* Sets lastName
*
* #param lastName New value for lastName.
**/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Gets address
*
* #return Value for address.
**/
public String getAddress() {
return address;
}
/**
* Sets address
*
* #param address New value for address.
**/
public void setAddress(String address) {
this.address = address;
}
/** {#inheritDoc} **/
#Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Customer))
return false;
Customer that = (Customer)o;
if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null)
return false;
if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null)
return false;
if (address != null ? !address.equals(that.address) : that.address != null)
return false;
return true;
}
/** {#inheritDoc} **/
#Override public int hashCode() {
int res = firstName != null ? firstName.hashCode() : 0;
res = 31 * res + (lastName != null ? lastName.hashCode() : 0);
res = 31 * res + (address != null ? address.hashCode() : 0);
return res;
}
/** {#inheritDoc} **/
#Override public String toString() {
return "Customer [" +
"firstName=" + firstName + ", " +
"lastName=" + lastName + ", " +
"address=" + address +
"]";
}
}
Model class of Item
package infoh415.project.model;
import java.io.Serializable;
/**
* Item definition.
*
* This file was generated by Ignite Web Console (11/26/2017, 10:52)
**/
public class Item implements Serializable {
/** */
private static final long serialVersionUID = 0L;
private int itemId;
/** Value for name. */
private String name;
/** Value for brand. */
private String brand;
/** Value for type. */
private String type;
/** Value for manufacturer. */
private String manufacturer;
/** Value for description. */
private String description;
public Item(String name, String brand, String type, String manufacturer, String description) {
this.name = name;
this.brand = brand;
this.type = type;
this.manufacturer = manufacturer;
this.description = description;
}
public Item(int itemId, String name, String brand, String type, String manufacturer, String description) {
this.itemId = itemId;
this.name = name;
this.brand = brand;
this.type = type;
this.manufacturer = manufacturer;
this.description = description;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
/**
* Gets name
*
* #return Value for name.
**/
public String getName() {
return name;
}
/**
* Sets name
*
* #param name New value for name.
**/
public void setName(String name) {
this.name = name;
}
/**
* Gets brand
*
* #return Value for brand.
**/
public String getBrand() {
return brand;
}
/**
* Sets brand
*
* #param brand New value for brand.
**/
public void setBrand(String brand) {
this.brand = brand;
}
/**
* Gets type
*
* #return Value for type.
**/
public String getType() {
return type;
}
/**
* Sets type
*
* #param type New value for type.
**/
public void setType(String type) {
this.type = type;
}
/**
* Gets manufacturer
*
* #return Value for manufacturer.
**/
public String getManufacturer() {
return manufacturer;
}
/**
* Sets manufacturer
*
* #param manufacturer New value for manufacturer.
**/
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
/**
* Gets description
*
* #return Value for description.
**/
public String getDescription() {
return description;
}
/**
* Sets description
*
* #param description New value for description.
**/
public void setDescription(String description) {
this.description = description;
}
/** {#inheritDoc} **/
#Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Item))
return false;
Item that = (Item)o;
if (name != null ? !name.equals(that.name) : that.name != null)
return false;
if (brand != null ? !brand.equals(that.brand) : that.brand != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (manufacturer != null ? !manufacturer.equals(that.manufacturer) : that.manufacturer != null)
return false;
if (description != null ? !description.equals(that.description) : that.description != null)
return false;
return true;
}
/** {#inheritDoc} **/
#Override public int hashCode() {
int res = name != null ? name.hashCode() : 0;
res = 31 * res + (brand != null ? brand.hashCode() : 0);
res = 31 * res + (type != null ? type.hashCode() : 0);
res = 31 * res + (manufacturer != null ? manufacturer.hashCode() : 0);
res = 31 * res + (description != null ? description.hashCode() : 0);
return res;
}
/** {#inheritDoc} **/
#Override public String toString() {
return "Item [" +
"name=" + name + ", " +
"brand=" + brand + ", " +
"type=" + type + ", " +
"manufacturer=" + manufacturer + ", " +
"description=" + description +
"]";
}
}
Can somebody please explain what the "class org.apache.ignite.IgniteCheckedException: Unknown pair [platformId=0, typeId=123254525]" error means and how to trace the cause of this issue - I already tried stepping through the Ignite code in debug mode, I know that in MarshallerContextImpl#getClassName the first line MappedName mappedName = cache.get(typeId); yields null for Item. But I do not understand why. Any help would be appreciated!! Thank you.
UPDATE:
Ignite version used: ignite-core 2.2.0
Update: content of loadCache:
private static void loadCache(IgniteCache<Integer, Item> cache) {
long start = System.currentTimeMillis();
// Start loading cache from persistent store on all caching nodes.
// cache.loadCache(null, ENTRY_COUNT);
cache.loadCache(null);
long end = System.currentTimeMillis();
System.out.println(">>> Loaded " + cache.size() + " keys with backups in " + (end - start) + "ms.");
}
Table definition of the Item table:
create table Item
(
item_id int not null
primary key,
name varchar(50) not null,
brand varchar(20) not null,
type varchar(20) not null,
manufacturer varchar(30) not null,
description varchar(200)
)
I can reproduce it when, in loadCaches(), I put something that isn't exactly the expected Item in the cache:
private void loadCache(IgniteCache<Integer, Item> cache, /* Ignite.binary() */ IgniteBinary binary) {
// Note the absence of package name here:
BinaryObjectBuilder builder = binary.builder("Item");
builder.setField("name", "a");
builder.setField("brand", "B");
builder.setField("type", "c");
builder.setField("manufacturer", "D");
builder.setField("description", "e");
builder.setField("itemId", 1);
cache.withKeepBinary().put(1, builder.build());
}
Please share your loadCaches method for scrutiny.
Related
I have an application in Java 8 Collecting Data of multiple Threads using BlockingQueue.
I need to perform comparison of samples.
But my application is very large, I implemented a mock application (Github) in Java 8.
I'm generating a chunk of bytes (really is random order).
The bytes are stored into ChunkDTO class.
I implemented a capturer the ChunkDTO in a List, code in Capturer class.
Each ChunkDTO of List is translated into a List of Samples (TimePitchValue exactly) returning a nested List (or List of List of TimePitchValue).
Later the nested List is transposed in order to performs comparisons between TimePitchValue with the same time value.
Due to enormous volume of TimePitchValue instances it's consumes huge time in my application.
Here some code (The complete functional Code is in Github) because is still large for this site).
public class Generator {
final static Logger LOGGER = Logger.getLogger("SampleComparator");
public static void main(String[] args) {
long previous = System.nanoTime();
final int minBufferSize = 2048;
int sampleRate = 8192;
int numChannels = 1;
int numBytesPerSample = 1;
int samplesChunkPerSecond = sampleRate / minBufferSize;
int minutes = 0;
int seconds = 10;
int time = 60 * minutes + seconds;
int chunksBySecond = samplesChunkPerSecond * numBytesPerSample * numChannels;
int pitchs = 32;
boolean signed = false;
boolean endianness = false;
AudioFormat audioformat = new AudioFormat(sampleRate, 8 * numBytesPerSample, numChannels, signed, endianness);
ControlDSP controlDSP = new ControlDSP(audioformat);
BlockingQueue<ChunkDTO> generatorBlockingQueue = new LinkedBlockingQueue<>();
Capturer capturer = new Capturer(controlDSP, pitchs, pitchs * time * chunksBySecond, generatorBlockingQueue);
controlDSP.getListFuture().add(controlDSP.getExecutorService().submit(capturer));
for (int i = 0; i < time * chunksBySecond; i++) {
for (int p = 0; p < pitchs; p++) {
ChunkDTO chunkDTO = new ChunkDTO(UtilClass.getArrayByte(minBufferSize), i, p);
LOGGER.info(String.format("chunkDTO: %s", chunkDTO));
try {
generatorBlockingQueue.put(chunkDTO);
} catch (InterruptedException ex) {
LOGGER.info(ex.getMessage());
}
}
try {
Thread.sleep(1000 / chunksBySecond);
} catch (Exception ex) {
}
}
controlDSP.tryFinishThreads(Thread.currentThread());
long current = System.nanoTime();
long interval = TimeUnit.NANOSECONDS.toSeconds(current - previous);
System.out.println("Seconds Interval: " + interval);
}
}
Capturer Class
public class Capturer implements Callable<Void> {
private final ControlDSP controlDSP;
private final int pitchs;
private final int totalChunks;
private final BlockingQueue<ChunkDTO> capturerBlockingQueue;
private final Counter intCounter;
private final Map<Long, List<ChunkDTO>> mapIndexListChunkDTO = Collections.synchronizedMap(new HashMap<>());
private volatile boolean isRunning = false;
private final String threadName;
private static final Logger LOGGER = Logger.getLogger("SampleComparator");
public Capturer(ControlDSP controlDSP, int pitchs, int totalChunks, BlockingQueue<ChunkDTO> capturerBlockingQueue) {
this.controlDSP = controlDSP;
this.pitchs = pitchs;
this.totalChunks = totalChunks;
this.capturerBlockingQueue = capturerBlockingQueue;
this.intCounter = new Counter();
this.controlDSP.getListFuture().add(this.controlDSP.getExecutorService().submit(() -> {
while (intCounter.getValue() < totalChunks) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
capturerBlockingQueue.add(new ChunkDTOStopper());
}));
this.threadName = this.getClass().getSimpleName();
}
#Override
public Void call() throws Exception {
long quantity = 0;
isRunning = true;
while (isRunning) {
try {
ChunkDTO chunkDTO = capturerBlockingQueue.take();
if (chunkDTO instanceof ChunkDTOStopper) {
break;
}
//Find or Create List (according to Index) to add the incoming Chunk
long index = chunkDTO.getIndex();
int sizeChunk = chunkDTO.getChunk().length;
List<ChunkDTO> listChunkDTOWithIndex = getListChunkDTOByIndex(chunkDTO);
//When the List (according to Index) is completed and processed
if (listChunkDTOWithIndex.size() == pitchs) {
mapIndexListChunkDTO.remove(index);
TransposerComparator transposerComparator = new TransposerComparator(controlDSP, controlDSP.getAudioformat(), index, sizeChunk, listChunkDTOWithIndex);
controlDSP.getListFuture().add(controlDSP.getExecutorService().submit(transposerComparator));
}
quantity++;
intCounter.setValue(quantity);
LOGGER.info(String.format("%s\tConsumes:%s\ttotal:%05d", threadName, chunkDTO, quantity));
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
LOGGER.info(String.format("%s\tReceived:%05d\tQty:%s\tPitchs:%s\tEND\n", threadName, quantity, quantity / pitchs, pitchs));
return null;
}
private List<ChunkDTO> getListChunkDTOByIndex(ChunkDTO chunkDTO) {
List<ChunkDTO> listChunkDTOWithIndex = mapIndexListChunkDTO.get(chunkDTO.getIndex());
if (listChunkDTOWithIndex == null) {
listChunkDTOWithIndex = new ArrayList<>();
mapIndexListChunkDTO.put(chunkDTO.getIndex(), listChunkDTOWithIndex);
listChunkDTOWithIndex = mapIndexListChunkDTO.get(chunkDTO.getIndex());
}
listChunkDTOWithIndex.add(chunkDTO);
return listChunkDTOWithIndex;
}
}
TransposerComparator class.
The optimization required is in this code, specifically on transposedNestedList method.
public class TransposerComparator implements Callable<Void> {
private final ControlDSP controlDSP;
private final AudioFormat audioformat;
private final long index;
private final int sizeChunk;
private final List<ChunkDTO> listChunkDTOWithIndex;
private final String threadName;
private static final Logger LOGGER = Logger.getLogger("SampleComparator");
public TransposerComparator(ControlDSP controlDSP, AudioFormat audioformat, long index, int sizeChunk, List<ChunkDTO> listChunkDTOWithIndex) {
this.controlDSP = controlDSP;
this.audioformat = audioformat;
this.index = index;
this.sizeChunk = sizeChunk;
this.listChunkDTOWithIndex = listChunkDTOWithIndex;
this.threadName = this.getClass().getSimpleName() + "_" + String.format("%05d", index);
}
#Override
public Void call() throws Exception {
Thread.currentThread().setName(threadName);
LOGGER.info(String.format("%s\tINI", threadName));
try {
int numBytesPerSample = audioformat.getSampleSizeInBits() / 8;
int quantitySamples = sizeChunk / numBytesPerSample;
long baseTime = quantitySamples * index;
// Convert the List of Chunk Bytes to Nested List of TimePitchValue
List<List<TimePitchValue>> nestedListTimePitchValue = listChunkDTOWithIndex
.stream()
.map(chunkDTO -> {
return IntStream
.range(0, quantitySamples)
.mapToObj(time -> {
int value = extractValue(chunkDTO.getChunk(), numBytesPerSample, time);
return new TimePitchValue(chunkDTO.getPitch(), baseTime + time, value);
}).collect(Collectors.toList());
}).collect(Collectors.toList());
List<List<TimePitchValue>> timeNestedListTimePitchValue = transposedNestedList(nestedListTimePitchValue);
} catch (Exception ex) {
ex.printStackTrace();
LOGGER.log(Level.SEVERE, null, ex);
throw ex;
}
return null;
}
private static int extractValue(byte[] bytesSamples, int numBytesPerSample, int time) {
byte[] bytesSingleNumber = Arrays.copyOfRange(bytesSamples, time * numBytesPerSample, (time + 1) * numBytesPerSample);
int value = numBytesPerSample == 2
? (UtilClass.Byte2IntLit(bytesSingleNumber[0], bytesSingleNumber[1]))
: (UtilClass.byte2intSmpl(bytesSingleNumber[0]));
return value;
}
private static List<List<TimePitchValue>> transposedNestedList(List<List<TimePitchValue>> nestedList) {
List<List<TimePitchValue>> outNestedList = new ArrayList<>();
nestedList.forEach(pitchList -> {
pitchList.forEach(pitchValue -> {
List<TimePitchValue> listTimePitchValueWithTime = listTimePitchValueWithTime(outNestedList, pitchValue.getTime());
if (!outNestedList.contains(listTimePitchValueWithTime)) {
outNestedList.add(listTimePitchValueWithTime);
}
listTimePitchValueWithTime.add(pitchValue);
});
});
outNestedList.forEach(pitchList -> {
pitchList.sort(Comparator.comparingInt(TimePitchValue::getValue).reversed());
});
return outNestedList;
}
private static List<TimePitchValue> listTimePitchValueWithTime(List<List<TimePitchValue>> nestedList, long time) {
List<TimePitchValue> listTimePitchValueWithTime = nestedList
.stream()
.filter(innerList -> innerList.stream()
.anyMatch(timePitchValue -> timePitchValue.getTime() == time))
.findAny()
.orElseGet(ArrayList::new);
return listTimePitchValueWithTime;
}
}
I was testing:
With 5 Seconds in Generator class and the List<List<TimePitchValue>> timeNestedListTimePitchValue = transposedNestedList(nestedListTimePitchValue); line in TransposerComparator class, Commented 7 Seconds needed, Uncommented 211 Seconds needed.
With 10 Seconds in Generator class and the List<List<TimePitchValue>> timeNestedListTimePitchValue = transposedNestedList(nestedListTimePitchValue); line in TransposerComparator class, Commented 12 Seconds needed, Uncommented 574 Seconds needed.
I need to use the application at least 60 minutes.
With the purpose of reduce the needed (consumed) time, I have two ways:
I choose for short is to optimize the methods that I am currently using.
That should be successful but longer and is to use GPGPU, but I don't know where to start implementing it yet.
QUESTIONS
This Question is for the first way: What changes do you recommend in the code of the transposedNestedList method in order to improve speed?
Is there better alternative to use this Comparison?
outNestedList.forEach(pitchList -> {
pitchList.sort(Comparator.comparingInt(TimePitchValue::getValue).reversed());
});
In the restbucks project, an order has a private list of line items. I can't figure out how this field is exposed via rest api when getting a single order. It has no public getter or anything. Is it the mixins?
#Data, #NoArgsConstructor, #AllArgsConstructor, #EqualsAndHashCode are Lombok annotations, that are used to auto-generate a boilerplate code.
#Data
#Entity
#NoArgsConstructor(force = true)
#AllArgsConstructor
#EqualsAndHashCode(callSuper = false)
public class LineItem extends AbstractEntity {
private final String name;
private final int quantity;
private final Milk milk;
private final Size size;
private final MonetaryAmount price;
public LineItem(String name, MonetaryAmount price) {
this(name, 1, Milk.SEMI, Size.LARGE, price);
}
}
You can compare this code with delomboked one (welcome to Lombok-funs club )):
#Entity
public class LineItem extends AbstractEntity {
private final String name;
private final int quantity;
private final Milk milk;
private final Size size;
private final MonetaryAmount price;
public LineItem(String name, MonetaryAmount price) {
this(name, 1, Milk.SEMI, Size.LARGE, price);
}
public LineItem(String name, int quantity, Milk milk, Size size, MonetaryAmount price) {
this.name = name;
this.quantity = quantity;
this.milk = milk;
this.size = size;
this.price = price;
}
public LineItem() {
this.name = null;
this.quantity = 0;
this.milk = null;
this.size = null;
this.price = null;
}
public String getName() {
return this.name;
}
public int getQuantity() {
return this.quantity;
}
public Milk getMilk() {
return this.milk;
}
public Size getSize() {
return this.size;
}
public MonetaryAmount getPrice() {
return this.price;
}
public String toString() {
return "LineItem(name=" + this.getName() + ", quantity=" + this.getQuantity() + ", milk=" + this.getMilk() + ", size=" + this.getSize() + ", price=" + this.getPrice() + ")";
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof LineItem)) return false;
final LineItem other = (LineItem) o;
if (!other.canEqual((Object) this)) return false;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
if (this.getQuantity() != other.getQuantity()) return false;
final Object this$milk = this.getMilk();
final Object other$milk = other.getMilk();
if (this$milk == null ? other$milk != null : !this$milk.equals(other$milk)) return false;
final Object this$size = this.getSize();
final Object other$size = other.getSize();
if (this$size == null ? other$size != null : !this$size.equals(other$size)) return false;
final Object this$price = this.getPrice();
final Object other$price = other.getPrice();
if (this$price == null ? other$price != null : !this$price.equals(other$price)) return false;
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
result = result * PRIME + this.getQuantity();
final Object $milk = this.getMilk();
result = result * PRIME + ($milk == null ? 43 : $milk.hashCode());
final Object $size = this.getSize();
result = result * PRIME + ($size == null ? 43 : $size.hashCode());
final Object $price = this.getPrice();
result = result * PRIME + ($price == null ? 43 : $price.hashCode());
return result;
}
protected boolean canEqual(Object other) {
return other instanceof LineItem;
}
}
I want to deserialize a JSON array to a singly linked list in Java.
The definition of singly linked list is as the following:
public class SinglyLinkedListNode<T> {
public T value;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(final T value) {
this.value = value;
}
}
How to deserialize a JSON string such as [1,2,3,4,5] in to a singly linked list?
public void typeReferenceTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final ArrayList<Integer> intArray = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<ArrayList<Integer>>() {});
System.out.println(intArray);
// How to achieve this?
final ArrayList<Integer> intList = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<SinglyLinkedListNode<Integer>>() {});
System.out.println(intList);
}
Moreover, I want the SinglyLinkedListNode to be a first-class citizen the same as ArrayList, which can be used in all kinds of combinations, such as HashSet<SinglyLinkedListNode<Integer>>, SinglyLinkedListNode<HashMap<String, Integer>>.
For example, what happens if I want to deserialize [[1,2,3], [4,5,6]] into a ArrayList<SinglyLinkedListNode<Integer>> ?
As far as I know, a customized deserializer extending JsonDeserializer is not enough to do this.
When you want it to be deserialized to ArrayList<SinglyLinkedListNode<Integer>> for example. Your code specifies that is the type that expected. Therefore it should if a deserializer for SinglyLinkedListNode<Integer> is regeistered it will succeed.
From the jackson-user google group I get the right answer from #Tatu Saloranta.
The answer is simple: just implement the java.util.List interface, and Jackson will automatically serialize/deserialize between JSON array and SinglyLinkedListNode.
So I implement the java.util.List interface for SinglyLinkedListNode, the code is as the following:
import java.util.*;
import java.util.function.Consumer;
/**
* Singly Linked List.
*
* <p>As to singly linked list, a node can be viewed as a single node,
* and it can be viewed as a list too.</p>
*
* #param <E> the type of elements held in this collection
* #see java.util.LinkedList
*/
public class SinglyLinkedListNode<E>
extends AbstractSequentialList<E>
implements Cloneable, java.io.Serializable {
public E value;
public SinglyLinkedListNode<E> next;
/**
* Constructs an empty list.
*/
public SinglyLinkedListNode() {
value = null;
next = null;
}
/**
* Constructs an list with one elment.
*/
public SinglyLinkedListNode(final E value) {
this.value = value;
next = null;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* #param c the collection whose elements are to be placed into this list
* #throws NullPointerException if the specified collection is null
*/
public SinglyLinkedListNode(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final SinglyLinkedListNode<E> l = last();
final SinglyLinkedListNode<E> newNode = new SinglyLinkedListNode<>(e);
if (l == null)
this.value = e;
else
l.next = newNode;
modCount++;
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, SinglyLinkedListNode<E> succ) {
assert succ != null;
final SinglyLinkedListNode<E> prev = this.previous(succ);
final SinglyLinkedListNode<E> newNode = new SinglyLinkedListNode<>(e);
if (prev == null)
this.value = e;
else
prev.next = newNode;
modCount++;
}
/**
* Return the node before x.
*
* #param x current node
* #return the node before x
*/
private SinglyLinkedListNode<E> previous(final SinglyLinkedListNode<E> x) {
assert (x != null);
if (size() < 2) return null;
if (this == x) return null;
SinglyLinkedListNode<E> prev = new SinglyLinkedListNode<>();
prev.next = this;
SinglyLinkedListNode<E> cur = this;
while (cur != x) {
prev = prev.next;
cur = cur.next;
}
return prev;
}
/**
* Return the last node.
* #return the last node.
*/
private SinglyLinkedListNode<E> last() {
if (size() == 0) return null;
if (size() == 1) return this;
SinglyLinkedListNode<E> prev = new SinglyLinkedListNode<>();
prev.next = this;
SinglyLinkedListNode<E> cur = this;
while (cur != null) {
prev = prev.next;
cur = cur.next;
}
return prev;
}
/**
* Unlinks non-null node x.
*/
E unlink(SinglyLinkedListNode<E> x) {
assert x != null;
final E element = x.value;
final SinglyLinkedListNode<E> next = x.next;
final SinglyLinkedListNode<E> prev = previous(x);
if (prev == null) {
this.value = next.value;
this.next = next.next;
} else {
prev.next = next;
}
x.next = null;
modCount++;
return element;
}
/**
* #inheritDoc
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private SinglyLinkedListNode<E> lastReturned;
private SinglyLinkedListNode<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
assert isPositionIndex(index);
next = (index == size()) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size();
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.value;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
throw new UnsupportedOperationException();
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
unlink(lastReturned);
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.value = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size()) {
action.accept(next.value);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* #inheritDoc
*/
public int size() {
int size = 0;
if (value == null) return size;
SinglyLinkedListNode<E> cur = this;
while (cur != null) {
size++;
cur = cur.next;
}
return size;
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Returns the (non-null) Node at the specified element index.
*/
SinglyLinkedListNode<E> node(int index) {
assert isElementIndex(index);
SinglyLinkedListNode<E> x = this;
for (int i = 0; i < index; i++)
x = x.next;
return x;
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size();
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size();
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: " + size();
}
}
Here is the unit test code:
#Test public void typeReferenceTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final SinglyLinkedListNode<Integer> intList = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<SinglyLinkedListNode<Integer>>() {});
System.out.println(intList);
final ArrayList<SinglyLinkedListNode<Integer>> arrayOfList = objectMapper.readValue("[[1,2,3], [4,5,6]]",
new TypeReference<ArrayList<SinglyLinkedListNode<Integer>>>() {});
System.out.println(arrayOfList);
}
#Tatu Saloranta Thank you very much!
Here is my original blog, Deserialize a JSON Array to a Singly Linked List
Suppose a lucene index with fields : date, content.
I want to get all terms value and frequency of docs whose date is yesterday. date field is keyword field. content field is analyzed and indexed.
Pls help me with sample code.
My solution source is as follow ...
/**
*
*
* #param reader
* #param fromDateTime
* - yyyymmddhhmmss
* #param toDateTime
* - yyyymmddhhmmss
* #return
*/
static public String top10(IndexSearcher searcher, String fromDateTime,
String toDateTime) {
String top10Query = "";
try {
Query query = new TermRangeQuery("tweetDate", new BytesRef(
fromDateTime), new BytesRef(toDateTime), true, false);
final BitSet bits = new BitSet(searcher.getIndexReader().maxDoc());
searcher.search(query, new Collector() {
private int docBase;
#Override
public void setScorer(Scorer scorer) throws IOException {
}
#Override
public void setNextReader(AtomicReaderContext context)
throws IOException {
this.docBase = context.docBase;
}
#Override
public void collect(int doc) throws IOException {
bits.set(doc + docBase);
}
#Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
});
//
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43,
EnglishStopWords.getEnglishStopWords());
//
HashMap<String, Long> wordFrequency = new HashMap<>();
for (int wx = 0; wx < bits.length(); ++wx) {
if (bits.get(wx)) {
Document wd = searcher.doc(wx);
//
TokenStream tokenStream = analyzer.tokenStream("temp",
new StringReader(wd.get("content")));
// OffsetAttribute offsetAttribute = tokenStream
// .addAttribute(OffsetAttribute.class);
CharTermAttribute charTermAttribute = tokenStream
.addAttribute(CharTermAttribute.class);
tokenStream.reset();
while (tokenStream.incrementToken()) {
// int startOffset = offsetAttribute.startOffset();
// int endOffset = offsetAttribute.endOffset();
String term = charTermAttribute.toString();
if (term.length() < 2)
continue;
Long wl;
if ((wl = wordFrequency.get(term)) == null)
wordFrequency.put(term, 1L);
else {
wl += 1;
wordFrequency.put(term, wl);
}
}
tokenStream.end();
tokenStream.close();
}
}
analyzer.close();
// sort
List<String> occurterm = new ArrayList<String>();
for (String ws : wordFrequency.keySet()) {
occurterm.add(String.format("%06d\t%s", wordFrequency.get(ws),
ws));
}
Collections.sort(occurterm, Collections.reverseOrder());
// make query string by top 10 words
int topCount = 10;
for (String ws : occurterm) {
if (topCount-- == 0)
break;
String[] tks = ws.split("\\t");
top10Query += tks[1] + " ";
}
top10Query.trim();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
// return top10 word string
return top10Query;
}
My Phone table has a composite primary of phone number and id. id is also a foreign key to the Student table.
I am seeing the below error when I run it.
23:30:28,228 ERROR SqlExceptionHelper:147 - Column 'id' cannot be null
org.hibernate.exception.ConstraintViolationException: could not execute statement
Schema:
Table: student
Columns:
id (PK)
fName
lName
mName
Table: Phone
Columns:
phoneNumber (PK)
color
id(PK)(FK references to Student id)
Student.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
#Entity
#SuppressWarnings("serial")
public class Student implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String fName;
private String lName;
private String mname;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "id")
private Set<Phone> phones;
/**
* #return the fName
*/
public String getfName() {
return fName;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #return the lName
*/
public String getlName() {
return lName;
}
/**
* #return the mname
*/
public String getMname() {
return mname;
}
/**
* #return the phones
*/
public Set<Phone> getPhones() {
return phones;
}
/**
* #param fName
* the fName to set
*/
public void setfName(final String fName) {
this.fName = fName;
}
/**
* #param id
* the id to set
*/
public void setId(final int id) {
this.id = id;
}
/**
* #param lName
* the lName to set
*/
public void setlName(final String lName) {
this.lName = lName;
}
/**
* #param mname
* the mname to set
*/
public void setMname(final String mname) {
this.mname = mname;
}
/**
* #param phones
* the phones to set
*/
public void setPhones(final Set<Phone> phones) {
this.phones = phones;
}
}
Phone.java
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#IdClass(PhonePK.class)
#Entity
#SuppressWarnings("serial")
public class Phone implements Serializable {
#Id
private String phoneNumber;
// #Id
// #ManyToOne
// #JoinColumn(name = "id", insertable = false, updatable = false)
// private String id;
#Id
#ManyToOne
#JoinColumn(name = "id", insertable = false, updatable = false)
private Student student;
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
private String color;
/**
* #return the color
*/
public String getColor() {
return color;
}
/**
* #return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* #return the student
*/
public Student getStudent() {
return student;
}
/**
* #param color
* the color to set
*/
public void setColor(final String color) {
this.color = color;
}
/**
* #param phoneNumber
* the phoneNumber to set
*/
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* #param student
* the student to set
*/
public void setStudent(final Student student) {
this.student = student;
}
}
PhonePK.java
import java.io.Serializable;
#SuppressWarnings("serial")
public class PhonePK implements Serializable {
private String phoneNumber;
//private String id;
private Student student;
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
/**
* #return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* #return the student
*/
public Student getStudent() {
return student;
}
/**
* #param phoneNumber
* the phoneNumber to set
*/
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* #param student
* the student to set
*/
public void setStudent(final Student student) {
this.student = student;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PhonePK other = (PhonePK) obj;
if (phoneNumber == null) {
if (other.phoneNumber != null) {
return false;
}
} else if (!phoneNumber.equals(other.phoneNumber)) {
return false;
}
if (student == null) {
if (other.student != null) {
return false;
}
} else if (!student.equals(other.student)) {
return false;
}
// if (id == null) {
// if (other.id != null) {
// return false;
// }
// } else if (!id.equals(other.id)) {
// return false;
// }
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
result = prime * result + ((student == null) ? 0 : student.hashCode());
// result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">pwd</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
Main.java
import java.util.LinkedHashSet;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(final String args[]) {
Configuration configuration = new Configuration();
Transaction transaction = null;
configuration.addAnnotatedClass(Student.class);
configuration.addAnnotatedClass(Phone.class);
configuration.addAnnotatedClass(PhonePK.class);
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
System.out.println("Session Factory!!!!" + sessionFactory);
Session session = sessionFactory.openSession();
Student student = new Student();
student.setfName("Bob");
student.setlName("Buster");
Set<Phone> phones = new LinkedHashSet<Phone>();
Phone ph1 = new Phone();
ph1.setColor("Black");
ph1.setPhoneNumber("1111111111");
Phone ph2 = new Phone();
ph2.setColor("Blue");
ph2.setPhoneNumber("2222222222");
phones.add(ph1);
phones.add(ph2);
student.setPhones(phones);
try {
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Console output:
23:30:24,291 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
23:30:24,296 DEBUG SQL:104 - alter table Phone drop foreign key
FK_aoj0eivd0ap3drxnoyk4xj10q
23:30:25,613 DEBUG SQL:104 - drop table if exists Phone
23:30:25,967 DEBUG SQL:104 - drop table if exists Student
23:30:26,230 DEBUG SQL:104 - create table Phone (phoneNumber varchar(255) not null,
color varchar(255), id integer not null, primary key (phoneNumber, id))
23:30:26,731 DEBUG SQL:104 - create table Student (id integer not null auto_increment,
fName varchar(255), lName varchar(255), mname varchar(255), primary key (id))
23:30:26,792 DEBUG SQL:104 - alter table Phone add index FK_aoj0eivd0ap3drxnoyk4xj10q
(id), add constraint FK_aoj0eivd0ap3drxnoyk4xj10q foreign key (id) references Student
(id)
23:30:27,352 INFO SchemaExport:405 - HHH000230: Schema export complete
Session Factory!!!!org.hibernate.internal.SessionFactoryImpl#548997d1
23:30:27,823 DEBUG SQL:104 - insert into Student (fName, lName, mname) values (?, ?, ?)
23:30:27,886 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - Bob
23:30:27,887 TRACE BasicBinder:84 - binding parameter [2] as [VARCHAR] - Buster
23:30:27,888 TRACE BasicBinder:72 - binding parameter [3] as [VARCHAR] - <null>
23:30:28,005 DEBUG SQL:104 - select phone_.phoneNumber, phone_.id, phone_.color as
color2_0_ from Phone phone_ where phone_.phoneNumber=? and phone_.id=?
23:30:28,009 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - 1111111111
23:30:28,010 TRACE BasicBinder:72 - binding parameter [2] as [INTEGER] - <null>
23:30:28,102 DEBUG SQL:104 - select phone_.phoneNumber, phone_.id, phone_.color as
color2_0_ from Phone phone_ where phone_.phoneNumber=? and phone_.id=?
23:30:28,103 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - 2222222222
23:30:28,104 TRACE BasicBinder:72 - binding parameter [2] as [INTEGER] - <null>
23:30:28,222 DEBUG SQL:104 - insert into Phone (color, phoneNumber, id) values (?, ?,
?)
23:30:28,223 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - Black
23:30:28,224 TRACE BasicBinder:84 - binding parameter [2] as [VARCHAR] - 1111111111
23:30:28,224 TRACE BasicBinder:72 - binding parameter [3] as [INTEGER] - <null>
23:30:28,227 WARN SqlExceptionHelper:145 - SQL Error: 1048, SQLState: 23000
23:30:28,228 ERROR SqlExceptionHelper:147 - Column 'id' cannot be null
org.hibernate.exception.ConstraintViolationException: could not execute statement
at
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert
(SQLExceptionTypeDelegate.java:74)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert
(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert
(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert
(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate
(ResultSetReturnImpl.java:136)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch
(NonBatchingBatch.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert
(AbstractEntityPersister.java:3067)
at org.hibernate.persister.entity.AbstractEntityPersister.insert
(AbstractEntityPersister.java:3509)
at org.hibernate.action.internal.EntityInsertAction.execute
(EntityInsertAction.java:88)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:286)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions
(AbstractFlushingEventListener.java:339)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush
(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.
beforeTransactionCommit
(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit
(AbstractTransactionImpl.java:175)
at Main.main(Main.java:49)
Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'id' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate
(ResultSetReturnImpl.java:133)
... 14 more
23:30:28,323 INFO AbstractBatchImpl:195 - HHH000010:
On release of batch it still contained JDBC statements
you can create embeddale Primary key class.
#Embeddable
public class Phone_pk implements Serializable{
#ManyToOne(targetEntity=Student.class)
#JoinColumn(name="id", referencedColumnName="id")
#ForeignKey(name="Student_Phone_FK")
private Student student;
private String phoneNumber;
}
And use this as primary key in your phone class
#EmbeddedId
private Phone_pk PK;