I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
Technologies used:
Spring Boot 1.4.2.RELEASE, Spring 4.3.4.RELEASE, Thymeleaf 2.1.5.RELEASE, Tomcat Embed 8.5.6, Maven 3, Java 8
I have this classes
public class DeviceEvent {
public DeviceEvent(Device device) {
this.device = device;
}
private Device device;
private Long id;
private Double latitude;
private Double longitude;
private Date dateReceived;
private String message;
private Float rssi;
private Integer battery;
private Boolean alarm;
private Boolean processed;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Date getDateReceived() {
return dateReceived;
}
public void setDateReceived(Date dateReceived) {
this.dateReceived = dateReceived;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Float getRssi() {
return rssi;
}
public void setRssi(Float rssi) {
this.rssi = rssi;
}
public Integer getBattery() {
return battery;
}
public void setBattery(Integer battery) {
this.battery = battery;
}
public Boolean getAlarm() {
return alarm;
}
public void setAlarm(Boolean alarm) {
this.alarm = alarm;
}
public Boolean getProcessed() {
return processed;
}
public void setProcessed(Boolean processed) {
this.processed = processed;
}
}
but I got this error executing this test:
Device device = new Device("C380F");
DeviceEvent deviceEvent = new DeviceEvent(device);
deviceEvent.setId(Sequencer.getNextVal());
deviceEvent.setAlarm(Boolean.FALSE);
deviceEvent.setBattery(78);
deviceEvent.setDateReceived(new Date());
deviceEvent.setLatitude(50.834015);
deviceEvent.setLongitude(4.377885);
deviceEvent.setMessage("FAKE_MSG");
deviceEvent.setProcessed(Boolean.FALSE);
deviceEvent.setRssi((float)80);
repository.insert(deviceEvent);
...
#Override
public long insert(DeviceEvent newDeviceEvent) {
long id = Sequencer.getNextVal();
int numOfRowsAffected = jdbcTemplate.update(
"insert into T_DEVICE_EVENT (ID, DEVICE_ID, LATITUDE, LONGITUDE, MESSAGE, DATE_RECEIVED, RSSI, BATTERY, ALARM, PROCESSED) " +
" values (?,?,?,?,?,?,?,?,?,?);",
id,
newDeviceEvent.getDevice().getId(),
newDeviceEvent.getLatitude(),
newDeviceEvent.getLongitude(),
newDeviceEvent.getMessage(),
newDeviceEvent.getRssi(),
newDeviceEvent.getBattery(),
newDeviceEvent.getAlarm(),
0);
if (numOfRowsAffected==1) return id;
else return -1;
}
..
the table
CREATE TABLE IF NOT EXISTS t_device_event (
id bigint PRIMARY KEY,
device_id bigint NOT NULL,
latitude decimal NULL,
longitude decimal NULL,
message varchar(100) ,
date_received timestamp,
rssi float,
battery int,
alarm boolean,
processed boolean,
FOREIGN KEY (device_id) REFERENCES public.t_device(id));
the error:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [insert into T_DEVICE_EVENT (ID, DEVICE_ID, LATITUDE, LONGITUDE, MESSAGE, DATE_RECEIVED, RSSI, BATTERY, ALARM, PROCESSED) values (?,?,?,?,?,?,?,?,?,?);]; nested exception is java.sql.SQLSyntaxErrorException: incompatible data type in conversion
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:91)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:931)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:941)
at com.ideefecloud.iot.repository.JdbcDeviceEventRepository.insert(JdbcDeviceEventRepository.java:44)
at com.ideefecloud.iot.repository.JdbcDeviceEventRepositoryTests.testInsert(JdbcDeviceEventRepositoryTests.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.sql.SQLSyntaxErrorException: incompatible data type in conversion
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.throwError(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.setParameter(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.setObject(Unknown Source)
at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:454)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:238)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:169)
at org.springframework.jdbc.core.ArgumentPreparedStatementSetter.doSetValue(ArgumentPreparedStatementSetter.java:66)
at org.springframework.jdbc.core.ArgumentPreparedStatementSetter.setValues(ArgumentPreparedStatementSetter.java:47)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:875)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
... 34 more
Caused by: org.hsqldb.HsqlException: incompatible data type in conversion
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.types.DateTimeType.convertJavaToSQL(Unknown Source)
... 44 more
I think your columns/parameters are misaligned. The date_received specifically doesn't seem to have a corresponding parameter so it's trying to convert a float (RSSI) into a timestamp
Related
I use guava synchronizedSortedSetMultimap to save data:
public static final Multimap<TimestampedDeviceId, ParsedPayload> multimap = Multimaps.synchronizedSortedSetMultimap(
TreeMultimap.create(new Comparator<TimestampedDeviceId>() {
#Override
public int compare(TimestampedDeviceId o1, TimestampedDeviceId o2) {
return o1.compareTo(o2);
}
}, new Comparator<ParsedPayload>() {
#Override
public int compare(ParsedPayload o1, ParsedPayload o2) {
return o1.getCurrentPkgNum()-o2.getCurrentPkgNum();
}
}));
The key of the map is the combination of timestamp and devID:
#Data
#AllArgsConstructor
public class TimestampedDeviceId implements Comparable<TimestampedDeviceId> {
String deviceId;
TimeStamp timeStamp;
#Override
public int compareTo(TimestampedDeviceId o) {
// log.info("o:{},{}",o,timeStamp);
if(!deviceId.equals(o.deviceId)){
return deviceId.compareTo(o.deviceId);
}
else {
return timeStamp.compareTo(o.getTimeStamp());
} }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TimestampedDeviceId that = (TimestampedDeviceId) o;
return Objects.equals(deviceId, that.deviceId) &&
Objects.equals(timeStamp, that.timeStamp);
}
#Override
public int hashCode() {
return Objects.hash(deviceId, timeStamp);
}
}
And the data comes in order, when first data coming, I got the exception:
2021-03-18 10:03:06.284 INFO com.aier.camerawater.service.OnenetService - id:"668609823",total:28,current:1,time:{"day":18,"hour":10,"minute":3,"month":3,"second":4,"year":2021},exception:{}
java.lang.NullPointerException: null
at com.aier.camerawater.model.TimeStamp.compareTo(TimeStamp.java:39)
at com.aier.camerawater.model.TimestampedDeviceId.compareTo(TimestampedDeviceId.java:24)
at com.aier.camerawater.util.Common$1.compare(Common.java:32)
at com.aier.camerawater.util.Common$1.compare(Common.java:28)
at java.util.TreeMap.getEntryUsingComparator(TreeMap.java:376)
at java.util.TreeMap.getEntry(TreeMap.java:345)
at java.util.TreeMap.get(TreeMap.java:278)
at com.google.common.collect.AbstractMapBasedMultimap.put(AbstractMapBasedMultimap.java:184)
at com.google.common.collect.AbstractSetMultimap.put(AbstractSetMultimap.java:137)
at com.google.common.collect.TreeMultimap.put(TreeMultimap.java:74)
at com.google.common.collect.Synchronized$SynchronizedMultimap.put(Synchronized.java:636)
at com.aier.camerawater.service.OnenetService.parse(OnenetService.java:92)
at com.aier.camerawater.controller.OnenetController.receive(OnenetController.java:28)
at sun.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
It dosen't make sense why the first data cause the comoareTo method NPE.
Any help will be grateful
I am trying a very basic example of Spring Data Redis, where I want to store a User object in Redis and then return it:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
class BasicUser {
private String name;
private String surname;
private String emailAddress;
private Integer age;
}
#Test
public void storeUserInRedisWithRedisTemplateTest() {
BasicUser user = BasicUser
.builder()
.age(22)
.name("testuser")
.surname("testsurname")
.emailAddress("address#address.com")
.build();
redisTemplate.opsForValue().set("userWithTemplate", user, 10800);
BasicUser returnedUser = (BasicUser) redisTemplate.opsForValue().get("userWithTemplate");
assertThat(returnedUser.emailAddress, is(user.emailAddress));
}
The error is:
org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Invalid UTF-32 character 0x7b214063 (above 0x0010ffff) at char #2700, byte #10803); nested exception is java.io.CharConversionException: Invalid UTF-32 character 0x7b214063 (above 0x0010ffff) at char #2700, byte #10803)
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:152)
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:130)
at org.springframework.data.redis.core.AbstractOperations.deserializeValue(AbstractOperations.java:335)
at org.springframework.data.redis.core.AbstractOperations$ValueDeserializingRedisCallback.doInRedis(AbstractOperations.java:61)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:228)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:188)
at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:96)
at org.springframework.data.redis.core.DefaultValueOperations.get(DefaultValueOperations.java:53)
at com.kuluvalley.guru.server.service.UserSessionCacheServiceTest.storeUserInRedisWithRedisTemplateTest(UserSessionCacheServiceTest.java:123)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.io.CharConversionException: Invalid UTF-32 character 0x7b214063 (above 0x0010ffff) at char #2700, byte #10803)
at com.fasterxml.jackson.core.io.UTF32Reader.reportInvalid(UTF32Reader.java:195)
at com.fasterxml.jackson.core.io.UTF32Reader.read(UTF32Reader.java:158)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._loadMore(ReaderBasedJsonParser.java:250)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipWSOrEnd(ReaderBasedJsonParser.java:2354)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:672)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4340)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4189)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3266)
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:150)
... 40 more
In Redis, the value looks like:
[MANY MORE 0x00]
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00{\"#class\":\"com.org.BasicUser\",\"name\":\"testuser\",\"surname\":\"testsurname\",\"emailAddress\":\"address#address.com\",\"age\":22}"
The relevant Redis Configuration is as follows:
#Configuration
public class RedisConfig {
#Bean
public RedisConnectionFactory redisConnectionFactory(Environment env) {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(env.getRequiredProperty("redis.hostname"));
configuration.setPort(env.getProperty("redis.port", Integer.class, 6379));
return new LettuceConnectionFactory(configuration);
}
#Bean
public StringRedisTemplate redisTemplate(Environment env) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory(env));
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
I would expect this to just work as I am reading and writing the same data. Also the amount 0x00 is worrying. Is it best practice using Strings as values? What am I missing?
Basically, because you are using the wrong api not expected:
void set(K key, V value, long offset);
You should use:
void set(K key, V value, long timeout, TimeUnit unit);
with code:
redisTemplate.opsForValue().set("userWithTemplate", user, 10800, TimeUnit.SECONDS);
I have a problem with the Wicket 8 ModalWindow return value, I refer to Modal window, and it works fine.
I added a PageableListView to the instance (see Pageables Example) and it works fine.
In order to use DATABASE data, I use IModel to perform data query. I don’t set the query conditions on the home page, and they all work normally.
However, when I pass the value back to PageableListView through the modal window, a NullPointerException will appear in the modal window.
Thanks in advance.
Here is my code
ListModalTab.java
public class ListModalTab extends BasePage {
private static final long serialVersionUID = 1L;
#SpringBean
private TabHService oTabHService_;
private PageableListView cTabHListView_;
public ListModalTab() {
final Form cForm = new Form("form");
final Label result;
cForm.add(result = new Label("result", new PropertyModel<>(this, "result")));
result.setOutputMarkupId(true);
final ModalWindow modal1;
cForm.add(modal1 = new ModalWindow("modal1"));
modal1.setCookieName("modal-1");
modal1.setPageCreator(() -> new QueryModalTab(ListModalTab.this.getPageReference(), modal1));
modal1.setWindowClosedCallback(target -> target.add(cForm));
modal1.setOutputMarkupId(true);
modal1.setCloseButtonCallback(target -> {
setResult("Modal window 1 - close button");
return true;
});
cForm.add(new AjaxLink<Void>("showModal1") {
private static final long serialVersionUID = 1L;
#Override
public void onClick(AjaxRequestTarget target) {
modal1.show(target);
}
});
final WebMarkupContainer cContainer = new WebMarkupContainer("container");
cContainer.setOutputMarkupId(true);
cForm.add(cContainer);
/*
* Data query using IModel
*/
TabH oConstraintEntity = new TabH();
IModel mTabHListViewModel = new Model() {
public java.io.Serializable getObject() {
return (Serializable) oTabHService_.queryByTabH(oConstraintEntity);
}
};
/*
* Use string array data
*/
//final String[] names = { "Doe, John", "Presley, Elvis", "Presly, Priscilla",
// "Hasselhoff, David", "Moore, Demi", };
/*
* PageableListView is working properly if used with string array
*/
// PageableListView<String> listview = new PageableListView<String>("rows", Arrays.asList(names), 1) {
// #Override
// protected void populateItem(ListItem<String> item) {
// item.add(new Label("tabId", item.getModelObject()));
// }
// };
/*
* If the PageableListView is passed in using an IModel Object, the modal window will have a NullPointerException.
*/
PageableListView<TabH> listview = new PageableListView<TabH>("rows", mTabHListViewModel, 1) {
#Override
protected void populateItem(ListItem<TabH> item) {
final TabH oTabH = (TabH) item.getModelObject();
item.add(new Label("tabId", oTabH.getTabId()));
}
};
cContainer.add(listview);
cContainer.add(new AjaxPagingNavigator("navigator", listview));
this.add(cForm);
}
/**
* #return the result
*/
public String getResult() {
return result;
}
/**
* #param result
* the result to set
*/
public void setResult(String result) {
this.result = result;
}
private String result;}
QueryModalTab.java
public class QueryModalTab extends WebPage {
private static final long serialVersionUID = 1L;
private TabH tabH = new TabH();
public QueryModalTab(final PageReference modalWindowPage, final ModalWindow window) {
CompoundPropertyModel mTabH = new CompoundPropertyModel(tabH);
Form cForm = new Form("form", mTabH);
TextField cTabId = new TextField("tabId");
cForm.add(cTabId);
TextField cTabName = new TextField("tabName");
cForm.add(cTabName);
cForm.add(new AjaxLink<Void>("closeOK") {
private static final long serialVersionUID = 1L;
#Override
public void onClick(AjaxRequestTarget target) {
if (modalWindowPage != null)
((ListModalTab) modalWindowPage.getPage()).setResult("Modal window 1 - close link OK");
window.close(target);
}
});
/*
* NullPointerException appears in ((ListModalTab) modalWindowPage.getPage())
*/
AjaxSubmitLink cConfirm = new AjaxSubmitLink("confirm") {
#Override
protected void onSubmit(AjaxRequestTarget target) {
super.onSubmit(target);
if (modalWindowPage != null)
((ListModalTab) modalWindowPage.getPage()).setResult(tabH.getTabId());
ModalWindow.closeCurrent(target);
}
};
cForm.add(cConfirm);
cForm.add(new AjaxLink<Void>("closeCancel") {
private static final long serialVersionUID = 1L;
#Override
public void onClick(AjaxRequestTarget target) {
if (modalWindowPage != null)
((ListModalTab) modalWindowPage.getPage()).setResult("Modal window 1 - close link Cancel");
window.close(target);
}
});
this.add(cForm);
}
}
NullPointerException
Root cause:
java.lang.NullPointerException
at com.web.webpage.systempage.tab.QueryModalTab$2.onSubmit(QueryModalTab.java:52)
at org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink$1.onSubmit(AjaxSubmitLink.java:111)
at org.apache.wicket.ajax.form.AjaxFormSubmitBehavior$AjaxFormSubmitter.onSubmit(AjaxFormSubmitBehavior.java:223)
at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1251)
at org.apache.wicket.markup.html.form.Form.process(Form.java:946)
at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:770)
at org.apache.wicket.ajax.form.AjaxFormSubmitBehavior.onEvent(AjaxFormSubmitBehavior.java:176)
at org.apache.wicket.ajax.AjaxEventBehavior.respond(AjaxEventBehavior.java:151)
at org.apache.wicket.ajax.AbstractDefaultAjaxBehavior.onRequest(AbstractDefaultAjaxBehavior.java:598)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.internalInvoke(ListenerRequestHandler.java:306)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.invoke(ListenerRequestHandler.java:280)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.invokeListener(ListenerRequestHandler.java:222)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.respond(ListenerRequestHandler.java:208)
at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:912)
at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65)
at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:283)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253)
at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:262)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:204)
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:286)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I'm having a tough time figuring out the issue with Serialization in hadoop. Here's my class -
public class CrawlerTweet implements Serializable, Writable {
private static final long serialVersionUID = 1L;
private String keywords;
private List<TweetStatus> tweets;
private long queryTime = 0;
public CrawlerTweet() {}
public CrawlerTweet(String keys, List<TweetStatus> tweets, long queryTime){
this.keywords = keys;
this.tweets = tweets;
this.queryTime = queryTime;
}
public static CrawlerTweet read(DataInput in) throws IOException {
CrawlerTweet ts= new CrawlerTweet();
ts.readFields(in);
return ts;
}
#Override
public void readFields(DataInput din) throws IOException {
queryTime = din.readLong();
keywords = din.readLine();
tweets.clear();
IntWritable size = new IntWritable();
size.readFields(din);
int n = size.get();
while(n -- > 0) {
TweetStatus ts = new TweetStatus();
ts.readFields(din);
tweets.add(ts);
}
}
#Override
public void write(DataOutput dout) throws IOException {
dout.writeChars(keywords);
dout.writeLong(queryTime);
IntWritable size = new IntWritable(tweets.size());
size.write(dout);
for (TweetStatus ts : tweets)
ts.write(dout);
}
public String getKeywords(){
return keywords;
}
public List<TweetStatus> getTweets(){
return tweets;
}
public long getQueryTime(){
return queryTime;
}
}
If I implment both Serizable n WRitable interfaces, I get following exception,
java.lang.ClassNotFoundException: mydat.twitter.dto.CrawlerTweet
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:249)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:601)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1572)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1493)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1729)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1326)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at focusedCrawler.util.storage.socket.ServerConnectionHandler.buildRequestObject(ServerConnectionHandler.java:136)
at focusedCrawler.util.storage.socket.ServerConnectionHandler.run(ServerConnectionHandler.java:340)
And, if I implment Writable only, I get NotSerializableException -
Erro de comunicacao: bigdat.twitter.dto.CrawlerTweet
Dormindo 5 mls
`[21/JUN/2013:11:23:39] [SocketAdapterFactory] [produce] [hadoop22:3190]
Erro de comunicacao: bigdat.twitter.dto.CrawlerTweet
java.io.NotSerializableException: bigdat.twitter.dto.CrawlerTweet
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at focusedCrawler.util.storage.socket.StorageRemoteAdapter.serializeParamObject(StorageRemoteAdapter.java:113)
at focusedCrawler.util.storage.socket.StorageRemoteAdapter.defaultMethod(StorageRemoteAdapter.java:205)
at focusedCrawler.util.storage.socket.StorageRemoteAdapter.insert(StorageRemoteAdapter.java:289)
at focusedCrawler.util.storage.distribution.StorageRemoteAdapterReconnect.insert(StorageRemoteAdapterReconnect.java:213)
at bigdat.twitter.crawler.CrawlTwitter.download(Unknown Source)
at bigdat.twitter.crawler.CrawlTwitter.run(Unknown Source)
Further information extracted from comments:
CrawlerTweet is packaged in BDAnalytics16.jar file.
export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:/home/rgupta/bdAnalytics/lib/*
hadoop jar $jarpath/BDAnalytics16.jar bigdat.twitter.crawler.CrawlTwitter \
$crwlInputFile > $logsFldr/crawler_$1.log 2>&1 &
Help will be much appreciated!
Thx!
I have a slight problem that I don't know how to solve. Could you help me please?
When I am trying to persist entity I get next exception:
12:47:39,398 ERROR [org.black.dmitriy.entityHome.ScheduleHome] (http--127.0.0.1-8080-1) javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [org.black.dmitriy.entity.Schedule#1]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1333) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:859) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04]
at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04]
at org.jboss.seam.persistence.EntityManagerInvocationHandler.invoke(EntityManagerInvocationHandler.java:46) [jboss-seam.jar:2.3.0.Final]
at $Proxy81.persist(Unknown Source) at org.jboss.seam.framework.EntityHome.persist(EntityHome.java:84) [jboss-seam.jar:2.3.0.Final]
at org.black.dmitriy.entityHome.ConversationHome.tryPersist(ConversationHome.java:147) [ejb.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04]
at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04]
at org.jboss.seam.util.Reflections.invoke(Reflections.java:22) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.core.ConversationInterceptor.aroundInvoke(ConversationInterceptor.java:65) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.transaction.TransactionInterceptor$1.work(TransactionInterceptor.java:97) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.util.Work.workInTransaction(Work.java:61) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:186) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:104) [jboss-seam.jar:2.3.0.Final]
at org.black.dmitriy.entityHome.ScheduleHome_$$_javassist_seam_8.tryPersist(ScheduleHome_$$_javassist_seam_8.java) [ejb.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04]
at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04]
at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.parser.AstValue.invoke(AstValue.java:96) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.7-jbossorg-2.jar:]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158) [jboss-seam.jar:2.3.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:397) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_04]
I use seam 2.3, hibernate. I have one insert statement in my import.sql file:
INSERT INTO Schedules (id, name, dayCount, lessonCount, firstTermSize, secondTermSize, subgroupSize) VALUES(1, '2012/2013', 5, 8, 9, 9, 18)
which inserts one enity into table Schedules.
Then I create new Schedule entity throw web page using EntityHome
#Name("scheduleHome")
#Scope(ScopeType.CONVERSATION)
public class ScheduleHome extends ConversationHome<Schedule> {
private static final long serialVersionUID = 1L;
public ScheduleHome() {
}
#Override
protected boolean isUnique() {
Schedule schedule = getInstance();
Schedule foundSchedule = ScheduleDAO.instance().getByName(schedule.getName());
if ((foundSchedule != null) && (!foundSchedule.equals(schedule))) {
showExistsErrorMessage(getInstance().getName());
return false;
}
return true;
}
#Override
protected Schedule createInstance() {
return new Schedule();
}
#Override
public String getEditOutcome() {
return "scheduleEdit";
}
#Override
protected void prepareEntityForSaving() {
}
}
and the superclass
public abstract class ConversationHome<T> extends EntityHome<T> {
private static final long serialVersionUID = 1L;
private String parentView;
public boolean isParentViewExists() {
return parentView != null && parentView.length() > 0;
}
public void setParentView(String parentView) {
this.parentView = parentView;
}
public String getParentView() {
return parentView;
}
public abstract String getEditOutcome();
protected abstract void prepareEntityForSaving();
protected abstract boolean isUnique();
#Override
#Create
public void create() {
create(false);
}
protected void create(boolean createNestedConversation) {
Conversation conversation = Conversation.instance();
if (!createNestedConversation && conversation.isLongRunning()) {
getLog().debug("conversation already started, nested will not create(isLongRunning = #0, isNested = #1)", conversation.isLongRunning(), conversation.isNested());
} else {
conversation.begin(false, conversation.isLongRunning());
conversation.changeFlushMode(FlushModeType.MANUAL);
getLog().debug("create(isLongRunning = #0, isNested = #1, id = #2)", conversation.isLongRunning(), conversation.isNested(), conversation.getId());
}
super.create();
}
private boolean init(Long id) {
FacesContext context = FacesContext.getCurrentInstance();
setParentView(Pages.getViewId(context));
if (id != null) {
setId(id);
try {
getInstance();
getLog().debug("instance initialized #0", getInstance());
} catch (EntityNotFoundException e) {
getLog().error(e);
return false;
}
}
return true;
}
public String startEdit(Long id) {
getLog().debug("start editing #0", id);
if (init(id)) {
return getEditOutcome();
} else {
return cancel();
}
}
public String cancel() {
if (isManaged()) {
getEntityManager().refresh(getInstance());
}
return returnToParent();
}
#End
protected String returnToParent() {
if (isParentViewExists()) {
Conversation conversation = Conversation.instance();
getLog().debug("end conversation(id = #0, isLongRunning = #1, isNested = #2)",
conversation.getId(), conversation.isLongRunning(), conversation.isNested());
conversation.end(true);
return getParentView();
} else {
clearInstance();
return null;
}
}
public String tryPersist() {
if (isUnique()) {
try {
prepareEntityForSaving();
String outcome = persist();
if (!"failed".equals(outcome)) {
return returnToParent();
}
} catch (Exception e) {
getLog().error(getInstance(), e);
showSaveErrorMessage(e);
}
}
return "failed";
}
}
and when i try to persist it i get this exception. and message on web page
Save error with message: a different object with the same identifier value was already associated with the session: [org.black.dmitriy.entity.Schedule#1]
It seams that hibernate set id property to 1, but I already have entity with id = 1, because I manually created it throw import.sql.
Here is my Schedule entity :
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "Schedules")
public class Schedule {
#Id
#GeneratedValue
#Column(name = "id", nullable = false)
private Long id;
#NotNull
#Column(name = "name", nullable = false, length = 40)
private String name;
#Column(name = "dayCount")
private int dayCount = 5;
#Column(name = "lessonCount")
private int lessonCount = 8;
#Column(name = "firstTermSize")
private int firstTermSize = 9;
#Column(name = "secondTermSize")
private int secondTermSize = 9;
#Column(name = "subgroupSize")
private int subgroupSize = 18;
#OneToMany(mappedBy = "schedule", cascade = CascadeType.ALL, targetEntity = Faculty.class)
private List<Faculty> faculties = new ArrayList<>();
#OneToMany(mappedBy = "schedule", cascade = CascadeType.ALL, targetEntity = Building.class)
private List<Building> buildings = new ArrayList<>();
public Schedule() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDayCount() {
return dayCount;
}
public void setDayCount(int dayCount) {
this.dayCount = dayCount;
}
public int getLessonCount() {
return lessonCount;
}
public void setLessonCount(int lessonCount) {
this.lessonCount = lessonCount;
}
public int getFirstTermSize() {
return firstTermSize;
}
public void setFirstTermSize(int firstTermSize) {
this.firstTermSize = firstTermSize;
}
public int getSecondTermSize() {
return secondTermSize;
}
public void setSecondTermSize(int secondTermSize) {
this.secondTermSize = secondTermSize;
}
public int getSubgroupSize() {
return subgroupSize;
}
public void setSubgroupSize(int subgroupSize) {
this.subgroupSize = subgroupSize;
}
public List<Faculty> getFaculties() {
return faculties;
}
public void setFaculties(List<Faculty> faculties) {
this.faculties = faculties;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Schedule)) {
return false;
}
Schedule other = (Schedule) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
#Override
public String toString() {
return this.name;
}
}
As you can see there is #GeneratedValue annotation on id property, so I think that hibernate should generate id himself and hibernate should know that there is entity in database with id = 1, and set id in new entity = 2. But Hibernate sets id in new entity to 1.
Could you halp me please?
The problem was how hibernate generates your id's, it starts from 1. When it assigns 1 to an object before saving it into database, it sees a row with same id already exists in the database and causes the exception. The simple and natural solution of this problem is simply to restrict hibernate, so that it can not assign 1 as an id to any object of the concerning class (in your case).
Solution for mySql:
If you are using mySql, you can create table manually and set the auto increment like:
CREATE TABLE IF NOT EXISTS `testTable` (
`id` number(11) NOT NULL AUTO_INCREMENT,
...,
...,
...,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2; //assigning id by hibernate, will start from 2.
And in your domain class you can have id annotated like bellow:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
public long getId() {
....
}
GenerationType.AUTO by default uses auto increment in mySql. and after setting AUTO_INCREMENT=2 hibernate will start assigning id's from 2 (hence 1 is skipped).
Solution for Oracle:
The same thing for oracle can be done if you restrict hibernate use a "sequence" and you set the initial point of the sequence as your wish. You can create a sequence to be start from 2 and increment by 1 like bellow:
create sequence idSequence
start with 2
increment by 1
maxvalue 9999999999999;
And you can specify your sequence to be used to generate id's of your domain class's object like bellow:
#Id
#SequenceGenerator(name = "idGeneratorSeq", sequenceName = "idSequence")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "idGeneratorSeq")
#Column(name = "ID")
public long getId() {
....
}
And your problem is sovled.
Do the following steps before calling persist() method.
First detach your current instance
getEntityManager().detach(getInstance());
Now set its Id to null
getInstance().setId(null);
Now persist
String outcome = persist();