Eager loading in Hibernate doesnt work, referenced attrribute has null values - database
i have a hibernate problem, probably due to lazy/eager loading or something similiar. I have a model class student and a model class century.
The student has an attribute century. Before I save the stdent in the dao i save the referenced century. But when I save the student, the century is null everywhere, except for it's name.
I tried
#Fetch(FetchMode.JOIN),
#ManyToOne(fetch = FetchType.EAGER) and getHibernateTemplate().initialize(student.getCentury());
so far but nothing will work.
Some ideas would be great, thanks in advance!
Student class:
// #Fetch(FetchMode.JOIN)
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "CENTURY_ID")
public Century getCentury() {
return century;
}
StudentDao:
load-method inherited from SuperDao:
#SuppressWarnings("unchecked")
public T load(Long id) {
T object = (T) getSession().get(
classOfData, id);
log.error(String.format("%s with id %d loaded.", CLASS_NAME_OF_DATA, id));
if (object == null) {
log.error("Object not found");
}
return object;
}
save method in StudentDao:
#Override
public Student save(Student student) throws HibernateException {
// getHibernateTemplate().initialize(student.getCentury());
log.error("Saving student:" + student.toString());
Century century = centuryDao.load(student.getCentury().getId());
System.out.println("instudentdao:" + century.getManiple());
centuryDao.save(student.getCentury());
getSession().saveOrUpdate(student);
log.error(String.format("Student with id %d saved.", student.getId()));
return student;
}
StudentAction load method is passed down to Dao:
private void loadStudent(String id) {
create = request.getParameter("mode").equals("create");
edit = request.getParameter("mode").equals("edit");
view = request.getParameter("mode").equals("view");
if (request.getParameter("mode").equals("create"))
student = new Student();
else
student = studentService.load(Long.valueOf(id));
}
log for (fetch = FetchType.EAGER)
2013-11-17 13:15:59,819 ERROR http-bio-8080-exec-9 - <Saving student:Student [id=1, firstName=hans, lastName=wurst, gender=null, city=HAMBURG, postalCode=22123, street=SHEMALESTREET, streetNumber=23, company=Company [id=null, name1=OLE, name2=null, nameShort=null, city=null, postalCode=null, street=null, streetNumber=null, email=null, phone=null, fax=null, status=null, supervisors=null], phone=1234123, email=olko#olko.olko, century=Century [id=null, name=Zenturie, maniple=null, students=null], birthday=Sun Jan 01 00:00:00 CET 2012, birthPlace=MUELLTONNE, userId=123, addressAddition=, status=ACTIVE, supervisor=Supervisor [id=null, firstName=null, lastName=, company=null, email=null, phone=null]]>
log for #JoinColumn(name = "CENTURY_ID")
2013-11-17 13:22:25,266 ERROR http-bio-8080-exec-10 - <Saving student:Student [id=1, firstName=hans, lastName=wurst, gender=null, city=HAMBURG, postalCode=22123, street=SHEMALESTREET, streetNumber=23, company=Company [id=null, name1=OLE, name2=null, nameShort=null, city=null, postalCode=null, street=null, streetNumber=null, email=null, phone=null, fax=null, status=null, supervisors=null], phone=1234123, email=olko#olko.olko, century=Century [id=null, name=Zenturie, maniple=null, students=null], birthday=Sun Jan 01 00:00:00 CET 2012, birthPlace=MUELLTONNE, userId=123, addressAddition=, status=ACTIVE, supervisor=Supervisor [id=null, firstName=null, lastName=, company=null, email=null, phone=null]]>
log for initialize()
2013-11-17 13:25:01,381 ERROR http-bio-8080-exec-10 - <Saving student:Student [id=1, firstName=hans, lastName=wurst, gender=null, city=HAMBURG, postalCode=22123, street=SHEMALESTREET, streetNumber=23, company=Company [id=null, name1=OLE, name2=null, nameShort=null, city=null, postalCode=null, street=null, streetNumber=null, email=null, phone=null, fax=null, status=null, supervisors=null], phone=1234123, email=olko#olko.olko, century=Century [id=null, name=Zenturie, maniple=null, students=null], birthday=Sun Jan 01 00:00:00 CET 2012, birthPlace=MUELLTONNE, userId=123, addressAddition=, status=ACTIVE, supervisor=Supervisor [id=null, firstName=null, lastName=, company=null, email=null, phone=null]]>
Related
Apache Flink -TumblingProcessingTimeWindows - Incorrect calculation Start-End
it's very simple example:env.keyBy(value -> (...)) .window(TumblingProcessingTimeWindows.of(Time.hours(24))).addSink(); ................ public Collection<TimeWindow> assignWindows(){ final long now = context.getCurrentProcessingTime(); long start = TimeWindow.getWindowStartWithOffset(now, offset, size); // the value "now" is correct = 1603379120043 (Date in your timezone*: 10/22/2020, 12:05:20 PM GMT-0300 (-03)) // the value "start" is 1603324800000 (Date in your timezone*: 10/21/2020, 9:00:00 PM GMT-0300 (-03) : ???!!!!! // I should started yesterday ??? // As the result: public TimeWindow(long start, long end) { this.start = start; //1603324800000 - Date in your timezone*: 10/21/2020, 9:00:00 PM GMT-0300 (-03) this.end = end; //1603411200000 - Date in your timezone*: 10/22/2020, 9:00:00 PM GMT-0300 (-03)} So, my job with 24h TumblingProcessingTimeWindows starting now at 10/22/2020, 12:05:20 PM will be finished today at 9:00:00 PM === 9 hours instead of 24 hours Some solutions, please ?
By default, Flink's windows are aligned to the epoch, not to the time when they are created. So a 24 hour window will end at midnight UTC. You can use the optional offset parameter to shift the window boundaries.
transaction isolation level (READ UNCOMMITTED) of Spring Batch
I want to set transaction isolation level to READ UNCOMMITTED, but is doesn't work. Here is my job source. TestJobConfiguration.java #Slf4j #Configuration public class TestJobConfiguration { #Autowired private JobBuilderFactory jobBuilders; #Autowired private CustomJobExecutionListener customJobExecutionListener; #Autowired private JdbcTemplate jdbcTemplate; #Autowired private StepBuilderFactory stepBuilders; #Bean(name = "testJob") public Job job() { JobBuilder jobBuilder = jobBuilders.get("testJob").listener(customJobExecutionListener); Step step = stepBuilders.get("testStep").tasklet(count()).transactionAttribute(transactionAttr()) .build(); return jobBuilder.start(step).build(); } public TransactionAttribute transactionAttr() { RuleBasedTransactionAttribute tr = new RuleBasedTransactionAttribute(); tr.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED); return tr; } public Tasklet count() { return new Tasklet() { #Override public RepeatStatus execute(StepContribution contribution, ChunkContext context) { StringBuilder countSql = new StringBuilder(); countSql.append(" SELECT COUNT(id)"); countSql.append(" FROM user"); log.debug("test start"); int count = jdbcTemplate.queryForObject(countSql.toString(), Integer.class); contribution.incrementWriteCount(count); log.debug("test end"); log.debug("count : {}", count); return RepeatStatus.FINISHED; } }; } } I executed below sql statement in Microsoft SQL Server Management Studio, and executed TestJob. begin tran delete from user I expected to complete job, but it stopped at sql execution point. My log is below. ... 2017-08-29T12:21:23.555+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test start When I change my sql statement, countSql.append(" SELECT COUNT(id)"); to countSql.append(" SELECT COUNT(id) WITH (READUNCOMMITTED)"); it works. ... 2017-08-29T13:44:43.692+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test start 2017-08-29T13:44:43.726+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test end 2017-08-29T13:44:43.726+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : count : 15178 2017-08-29T13:44:43.747+09:00 INFO --- [ main] c.p.l.b.l.CustomJobExecutionListener : <!----------------------------------------------------------------- Protocol for testJob Started : Tue Aug 29 13:44:43 KST 2017 Finished : Tue Aug 29 13:44:43 KST 2017 Exit-Code : COMPLETED Exit-Descr. : Status : COMPLETED Job-Parameter: date=2017-08-29 13:44:43 +0900 JOB process time : 0sec -----------------------------------------------------------------> Why doesn't work isolation level of transaction attribute??
apache-flink: sliding window in output
I'm currently coding a small application to understand the sliding windowing in FLINK (with data input from a APACHE-KAFKA topic): //Split kafka stream by comma and create tuple DataStream<Tuple3<String, Integer, Date>> parsedStream = stream .map((line) -> { String[] cells = line.split(","); return new Tuple3(cells[1], Integer.parseInt(cells[4]), f.parse(cells[2])); }); DataStream<Tuple3<String, Integer, Date>> parsedStreamWithTSWM = parsedStream .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple3<String, Integer, Date>>(Time.minutes(1)) { #Override public long extractTimestamp(Tuple3<String, Integer, Date> element) { return element.f2.getTime(); } }); //Sum values per windows and per id DataStream<Tuple3<String, Integer, Date>> AggStream = parsedStreamWithTSWM .keyBy(0) .window(SlidingEventTimeWindows.of(Time.minutes(30), Time.minutes(1))) .sum(1); AggStream.print(); Is it possible to improve my output (AggStream.print();) by adding the window details which produce the aggregation output ? $ tail -f flink-chapichapo-jobmanager-0.out (228035740000002,300,Fri Apr 07 14:42:00 CEST 2017) (228035740000000,28,Fri Apr 07 14:42:00 CEST 2017) (228035740000002,300,Fri Apr 07 14:43:00 CEST 2017) (228035740000000,27,Fri Apr 07 14:43:00 CEST 2017) (228035740000002,300,Fri Apr 07 14:44:00 CEST 2017) (228035740000000,26,Fri Apr 07 14:44:00 CEST 2017) (228035740000001,27,Fri Apr 07 14:44:00 CEST 2017) (228035740000002,300,Fri Apr 07 14:45:00 CEST 2017) (228035740000000,25,Fri Apr 07 14:45:00 CEST 2017) Thank you in advance
You can use the generic function apply where you have access to Window info. public interface WindowFunction<IN, OUT, KEY, W extends Window> extends Function, Serializable { /** * Evaluates the window and outputs none or several elements. * * #param key The key for which this window is evaluated. * #param window The window that is being evaluated. * #param input The elements in the window being evaluated. * #param out A collector for emitting elements. * * #throws Exception The function may throw exceptions to fail the program and trigger recovery. */ void apply(KEY key, W window, Iterable<IN> input, Collector<OUT> out) throws Exception; } See docs
How to pause a Camel Quartz2 timer in a suspended route?
The following unit test tries a quartz2 route that triggers each second: import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class CamelQuartzTest extends CamelTestSupport { static private String routeId = "test-route"; #Test public void testSuspendRoute() throws Exception { // arrange MockEndpoint mock = getMockEndpoint("mock:result"); // act System.out.println("context.start()"); context.start(); Thread.sleep(2000); System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter())); System.out.println("context.startRoute()"); context.startRoute(routeId); Thread.sleep(2000); System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter())); System.out.println("context.suspendRoute()"); context.suspendRoute(routeId); Thread.sleep(2000); System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter())); System.out.println("context.resumeRoute()"); context.resumeRoute(routeId); Thread.sleep(2000); System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter())); System.out.println("context.stop()"); context.stop(); System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter())); // assert assertEquals(4, mock.getReceivedCounter()); } #Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("quartz2://testtimer?cron=0/1+*+*+?+*+*") .autoStartup(false) .routeId(routeId) .setBody() .simple("${header.triggerName}: ${header.fireTime}") .to("mock:result", "stream:out"); } }; } } Result output: context.start() receivedCounter = 0 context.startRoute() testtimer: Tue Oct 21 10:06:38 CEST 2014 testtimer: Tue Oct 21 10:06:39 CEST 2014 receivedCounter = 2 context.suspendRoute() receivedCounter = 2 context.resumeRoute() testtimer: Tue Oct 21 10:06:41 CEST 2014 testtimer: Tue Oct 21 10:06:41 CEST 2014 testtimer: Tue Oct 21 10:06:42 CEST 2014 testtimer: Tue Oct 21 10:06:43 CEST 2014 receivedCounter = 6 context.stop() receivedCounter = 6 After resuming the route, the result shows 4 incoming triggers, while 2 were expected. Apparently, the quartz2 timer keeps firing while the route is suspended. How can I make quartz2 take a pause while the route is suspended?
Found the root cause: if a quartz job is suspended for a while, and resumed again, the default behavior of quartz is to catch up the triggers, aka "misfires", that were missed during the suspended period. I did not find a way the switch off this misfire behavior. However, decreasing the misfire threshold from 60 seconds to 500 ms helped in my case. This can be done by copying the default quartz.properties from quartz-<version>.jar to org/quartz/quartz.properties in the default classpath, and overrule the misfire threshold: # Properties file for use by StdSchedulerFactory # to create a Quartz Scheduler Instance. # This file overrules the default quartz.properties file in the # quartz-<version>.jar # org.quartz.scheduler.instanceName: DefaultQuartzScheduler org.quartz.scheduler.rmi.export: false org.quartz.scheduler.rmi.proxy: false org.quartz.scheduler.wrapJobExecutionInUserTransaction: false org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool org.quartz.threadPool.threadCount: 10 org.quartz.threadPool.threadPriority: 5 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true # default threshold: 60 seconds #org.quartz.jobStore.misfireThreshold: 60000 # overruled threshold: 500 ms, to prevent superfluous triggers after resuming # a quartz job org.quartz.jobStore.misfireThreshold: 500 org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
How to set the Am and Pm value to the Time Picker In windows phone 7 C#
i am using time picker in windows phone to add the event i am setting time ex 2.30 pm and i am stored the value in db next in update page i am setting the value to timepicker the value getting form database Code to set the value for time picker `updateEventTimePicker.Value = new DateTime(Convert.ToInt32(eventdatee[2]), Convert.ToInt32(eventdatee[1]), Convert.ToInt32(eventdatee[0]), Convert.ToInt32(eventTimee[0]), Convert.ToInt32(eventTimee[1]),1);` the problem is when i add in db the time was 2.30 pm but when i retrieve the value it sets 2.30 am how to set the AM and PM value
you cannot set the am or pm in the DateTime class. It is in a 24 hr format. you can use this function i wrote to get your hour or minute in a 24 hr format. public string [] get24hrFormat(string [] eventTime, string amOrpm) { amOrpm=amOrpm.ToLower(); string [] newTime= new string[2]; if(amOrpm=="am") { newTime[0]=eventTime[0]; newTime[1]=eventTime[1]; return newTime; } else { if (amOrpm == "pm") { if (eventTime[0] != "12") { newTime[0] = eventTime[0] + 12; newTime[1] = eventTime[1]; } else { newTime[0] = eventTime[0]; newTime[1] = eventTime[1]; } } return newTime; } }