Validate nested Transaction settings with Spring and Spring Boot

The Spring Framework has had an outstanding, declarative Transaction management for years now.
The configurable options maybe overwhelming at first, but important to accommodate many different scenarios.

Three of them stick out: propagation, isolation and to some lesser extend, read-only mode (more on that a bit later)

  • propagation describes what happens if a transaction is to be opened inside the scope of an already existing transaction
  • isolation determines among other whether one transaction can see uncommitted writes from another
  • read-only can be used as a hint when user code only executes reads

I wrote “to some lesser extend” regarding read-only as read-only transactions can be a useful optimization in some cases, such as when you use Hibernate. Some underlying implementations treat them as hints only and don’t actually prevent writes. For a full description of things, have a look at the reference documentation on transaction strategies.

Note: A great discussion on how setting read-only to true can affect performance in a positive way with Spring 5.1 and Hibernate 5.3 can be find in the Spring Ticket SPR-16956.

Some of the transactions settings are contradicting in case of nested transaction scenarios. The documentation says:

By default, a participating transaction joins the characteristics of the outer scope, silently ignoring the local isolation level, timeout value, or read-only flag (if any).

This service here is broken in my perception. It explicitly declare a read-only transaction and than calls a save on a Spring Data repository:

import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
 
@Service
public class BrokenService {
	private final ThingRepository thingRepository;
 
	public BrokenService(ThingRepository thingRepository) {
		this.thingRepository = thingRepository;
	}
 
	@Transactional(readOnly = true)
	public ThingEntity tryToWriteInReadOnlyTx() {
		return this.thingRepository.save(new ThingEntity("A thing"));
	}
}

This can be detected by using a PlatformTransactionManager that supports validation of existing transactions. The JpaTransactionManager does this as well as Neo4js Neo4jTransactionManager (both extending AbstractPlatformTransactionManager).

To enable validation for JPA’s transaction manager in a Spring Boot based scenario, just make use of the provided PlatformTransactionManagerCustomizer interface. Spring Boots autoconfiguration calls them with the corresponding transaction manager:

import org.springframework.boot.autoconfigure.transaction.PlatformTransactionManagerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
 
@Configuration
class TransactionManagerConfiguration {
 
	@Bean
	public PlatformTransactionManagerCustomizer<AbstractPlatformTransactionManager> transactionManagementConfigurer() {
		return (AbstractPlatformTransactionManager transactionManager) -> transactionManager
			.setValidateExistingTransaction(true);
	}
}

In the unlikely scenario you’re not using Spring Boot, you can always let Spring inject an EntityManagerFactory or for example Neo4j’s SessionFactory and create and configure the corresponding transaction manager yourself. My Neo4j tip does cover that as well.

If you try to execute the above service now, it’ll fail with an IllegalTransactionStateException indicating “save is not marked as read-only but existing transaction is”.

The question if a validation is possible arose in a discussion with customers. Funny enough, even working with Spring now for nearly 10 years, I never thought of that and always assumed it would validate those automatically but never tested it. Good to have learned something new, again.

Featured image on this post: Transaction by Nick Youngson CC BY-SA 3.0 Alpha Stock Images.

| Comments (0) »

25-Sep-18


Donating to Médecins Sans Frontières (Ärzte ohne Grenzen)

Some weeks ago, my friends Judith and Christian, who write great Steampunk, Fantasy and in the recent time science fiction books for whom I wrote this little Kotlin app had a good idea:

And I was like:

My book Spring Boot 2 has been a bestseller this year and I still got quite a decent revenue from arc42 by example that I co-authored with Gernot Starke and Stefan Zörner.

Keeping my promises, here are the numbers: My share of royalties of the arc42 by example book has been 112,15€ from June to August. Gernot, Stefan and I split revenues, so that is only my share. Gernot himself already donates through Leanpubs causes. I don’t have numbers from my publisher for Spring Boot Book. I therefore decided to round this number to 250€:



Me and my family have been incredibly lucky the last years and I’ more than happy that one can give. We live in Germany and despite some idiots on various (social) media, it’s really fortunate to live here. Health care is working, social system as well. We don’t have war but clean water, food and everything. We should not forget that this is by far not self-evident for many, many people on this planet-

| Comments (0) »

01-Sep-18


On becoming a Java Champion

July 2018 marks a personal highlight of mine. Just a bit after Rabea brought the news to our very own EuregJUG, the Java Champions account send this tweet out:

My name along this Java illuminaries. When I started this blog here more than twelve years ago, that was something I never even dreamed of. In 2006 the Java Champions program already existed but me, just been from university and vocal training for about 4 years or so, had no clue at all.

While getting my feet wet, I took inspiration from many of the people in the program, from their code, blog posts and talks. Not knowing that I would be working with them later in my life, even being direct colleagues with one of the founders like Eberhard Wolff. Even better: I’m lucky enough to call some of them my friends.

Java Champion was a long shot. I’m hopefully not the worst software engineer and architect out there, but I’m very far from knowing all the things. Quite the contrary. Did I know what a Java bridge method is until Gunnar brought this up on twitter? Do I know much about theoretical computer science? Hell no. I’m very sure that many people who I find very inspiring could forget more than I ever knew and still know more than I do.

So I must have done something else right and I’m happy with that. I just want to write some points down that might help others on their way:

On growth

Somewhen back in autumn 2014 I got Prokura in my company. I’m still not aware of an English word for that, but it means something along the lines that I can make and execute business decisions. My Prokura was only restricted in the way that I could not have closed the company.

Looking back, it was my bosses saying “we trust you to run this thing and also, this is our way of saying here, you’re explicitly technical lead, too.” Sadly, it didn’t come with a manual. At this point I was already more than 12 years at ENERKO INFORMATIK. I had grown in this time, but mostly on many technical levels. Things I learned include SQL, PL/SQL, XML, XSLT, Java (obviously), Spring (more obvious), we did Groovy at some point, not speaking of all the Swing based stuff I wrote and AFAIK ENERKO still runs an Oracle Database Dictionary based ORM I invented.

But could I lead a team? That was hard for me for several reasons. The company didn’t have had much fluctuation (and still hasn’t), so one did basically “grew up” with one another and it’s a weird situation if one person suddenly changes, either internally or externally.

Back then, I somewhen added the title line of a Nick Cave song to my personal site: “You’ve got to just, Keep on pushing, Keep on pushing, Push the sky away.” That has been my motto for quite some time.

I needed to grow beyond technical, “hard skills”. I tried and surprisingly, the feedback I got after leaving ENERKO INFORMATIK in 2017 was better than the impression I had of myself. I managed to hire two new engineers and they are still with the company which makes me quite happy.

In the end, I still felt I didn’t manage to achieve to anything. It’s weird how self perception and perception from others diverge. I left the company and I am working now at Neo4j, where I work in a small team with Gerrit Meier on Neo4j OGM and Spring Data and I couldn’t be happier with it.

Things come with a price

Most of the things “Spring” I learned on working with and on Daily Fratze, a personal photo site I’m running since 2005. I really love that stuff and I learned so much by developing it. But: It ruined my sleep in the days between 2010 and 2013 (2013 was the year my 2nd kid was born), it made parts of my family time with the my 1st kid very hard. I wanted to “finish” stuff and basically didn’t do anything else in my spare time.

Partially the same happened during late 2014 and early 2015, coincident with the events described unter “Growth” when I developed biking.michael-simons.eu and a lot more of Spring Boot related stuff inside my company. I was at home but I wasn’t there. I came back from the office, ate, and went into my office.

At some point, I needed to step back and also visited a doctor to help me to cope with sleep issues and dark moods.

We have a good family life most of the time, though. My wife always kept my back and I tried to be awake early every morning to be there for my kids. It’s by far not self evident that someone tolerates a partner that uses every minute awake when the kids are in their beds for coding, reading technical stuff and so on.

I gave a lot of talks since the end of 2015 with some success. The talks I enjoyed the most have been on Spring Boot and database related stuff. All the things I can explain in the middle of the night. However: I was and I still am super nervous at least a week before a talk. That feeling doesn’t seem to go away. Doing those talks is much more work for me than writing things (for example a book as explained in this post).

On mentoring

I was astonished that during the last 3 years or so many people came to me and thanked me for inspiration. That’s one of the reasons I’m trying to write this down here. Something like being a Java Champion or also success in general is most often not something that happens in a void, without help and support.

Everything I did and keep on doing: I would not be able to do this without having support in my life, a growing sense of what is good for my health (both mind and body) and without having had good mentors in my life.

There was my boss Rainer Barluschke at ENERKO INFORMATIK who taught me that there’s so much more than technical problems to solve. That it’s worth going a detour if the end result fits. Who even introduced me to some topics that seems to be more of the esoteric kind back than, like spiritual growth.

My ex-colleague Silke Böhler, who challenged me in JavaLand 2015 with some good food for thoughts and later on with a line “work is fun, but has to be taken seriously anyway…”. Apart from that: It has been the little things that last and helped along the way.

I already mentioned the support of my family, but also a kid can be a mentor. It’s hard to describe, but having someone near me that most of the time is in a good mood compared to myself, helps on focussing and accentuating the good things.

Summing things up…

Don’t give up trying to reach your goals because other peoples success seems to be so easily achieved. In the end, people of a group engage in the same game, but start with different preconditions. Look for opportunities where you are

  • Allowed to learn
  • Be able to fulfill a meaningful task, with all given due diligence and seriousness
  • Be part of a team, IT is not a single players sport

And also

  • Find a good mentor
  • Become a mentor: Pass on what you learned
  • Keep interest in other things outside your job… Not everything is related to IT

Right now, I feel at peace with myself for the first time in about 5 years. Going over the midlife crises? Who knows… I’m thankful that I actually could push my sky away by magnitudes and the last year will be a year I will always remember.

For the near future I’m super thrilled to work on cool stuff with Neo4j and Spring Data, with having the latest release of Neo4j OGM 3.1.1 just out of the door and see what happens next.

I made some innuendo to some people (Ralf 😉) that I do have ideas for a next book and as a spoiler: If put this together, I’ll try to bring this post here, something along that one and some other ideas into a form that might be worth reading for more people.

| Comments (0) »

20-Aug-18


Spring Boots Configuration Metadata with Kotlin

Last week I decided to raffle a copy of my book (see Twitter) and I wrote a small Spring Boot Command Line Runner to raffle the retweeting winner as one does (see raffle-by-retweet, feel free to reuse this).

I wrote the application in Kotlin. Notice the use of @ConfigurationProperties in my application:

The lateinit attributes are not as nice as I want them to be, but I heard support for data-classes is coming. Anyway. A super useful thing with those configuration property classes are the metadata that can be generated for your IDE of choice, see Configuration Metadata. In a Java application it’s enough to add org.springframework.boot:spring-boot-configuration-processor as compile time dependency respectively as annotationProcessor dependency in a Gradle build.

For Kotlin, you have to use the kotlin-kapt-plugin. It takes care of annotation processing in Kotlin and Spring Boots annotation processor has to be declared in its scope like this:

apply plugin: 'kotlin-kapt'
 
dependencies {
    // Other dependencies omitted
 
    kapt("org.springframework.boot:spring-boot-configuration-processor")
}

To make IDEA recognize the generated sources (and also use the same folders for classes as the Gradle build), you can this as well:

apply plugin: 'idea'
 
idea {
    module {
        def kaptMain = file("${project.buildDir}/generated/source/kapt/main")
        sourceDirs += kaptMain
        generatedSourceDirs += kaptMain
 
        outputDir file("${project.buildDir}/classes/main")
        testOutputDir file("${project.buildDir}/classes/test")
    }
}

Find the full build script here.

| Comments (0) »

15-Jul-18


Cognitive therapy

The featured image on this post is from Cycologygear. I love their shirts and have several of them. Highly recommended products. If you need some new jerseys, go check their shop!

Some days ago, Simon Maple asked the following question on Twitter:

Let me tell you a story. I’m an avid cyclist and run this site for quit a while now. I’m commuting about 20 to 30 kilometers a day now for more than years by bike. Before I had kids, I was into mountain biking. Nowadays more road race. In short: I always considered myself “fit”. Seldom out of breath when going up some stairs etc.

The following picture has been taken in the summer of 2016 and though it was a marvelous moment with my kids on an old boat, I thought: Wow, is that really you? Age 36 back than…



I still felt fine though some shirts and a couple of trousers became a bit small. I ended 2016 with about 85kg (I’m 1.86m tall). In 2017 I did a lot of conferences and user groups, drank a lot of beer and spend my whole spare time in front of a computer writing on my second book and by summer of 2017, it really did show and wasn’t feeling fine at all.

Not only I reached around 88kg, I was perceived ill the whole spring, usually tired and in short: Did not feel good.

I have a history of overdoing things. Being it work, sports, eating and drinking, so I was a bit anxious if buying a Garmin vívosmart® HR+ and a one year subscription of myfitnesspal was a good idea. Especially the later triggered some long forgotten memories with me.

I bought both nevertheless and the result is great. Actually eating more conscious and getting back a feeling what food contains a certain amount of calories was the main win of using myfitnesspal. I configured the app with a target weight of 80kg and a pretty though number of maximum daily calorie intake. I’m a bit stubborn on these kinda things and I wouldn’t recommend it for everybody. Anyway: I reached my goal – starting in July 2017 – by the end of October 2017 and since then, I’m around 79kg, given or take.

The other important aspect for me was doing some stuff I didn’t usually do:



The first running activity in 2017 did hurt. My muscles and my mind: Am I that slow? That soon of of breath? Holy cow… I tracked it with the vívosmart mentioned above. About 4km with a pace of 7:49 min/km. Oh boy.

I kept running and by the end of September I managed reach paces around 6:10 min/km consistently. That’s when things started to hurt less and actually became fun. What doesn’t work for me and probably never will is sports in a gym. Essential for me is actually being outside. Running is considerably easier in autumn and winter than cycling: Not much equipment you have to take care for, just throw everything in to the washing machine and be done with it.

No sports without a battle of equipment and materials. I sold the vívosmart to my friend André and gave myself a nice birthday present, a Garmin fēnix® 5S, a device I could wear the whole day:



You can read about the fēnix 5S for example at DC Rainmaker. For me, it stood up to all it’s promises, especially a battery life for about 7 days with 3 or 4 trainings. I never really wanted a Smart Watch, quit the contrary, I’m a fan of analog watches, but I do like having some notifications on the watch, like text messages from my “favorite” contacts. I do like however the fitness tracker and it’s reminder to get up once in an hour. I’m the kind of person who – when in the flow or really deep done into a problem – doesn’t get up from the chair until problem solved or the bladder ultimately demands its rights, so that improved daily life (work).

I tried to use the sleep tracker, but I don’t like having something around my wrist in my sleep, but I did set the reminder to get into bed before midnight.

I both like Garmin Connect and Garmin Connect Mobile a lot. You’ll need the later on your smartphone to configure your device. Both works as expected. Sometimes the bluetooth connection gets lost but force quitting the app and restarting it helped always on iOS. Both apps offer some good insights. Not sure if they are physically viable but I do like the relative measures. Also, after using the device now for a year, I’m pretty happy with the running result of 725km:

   

What really baffled me is the step counter, though: I walked nearly 4000km in a year.

I managed to ran 3 half marathons since December 2017, two of them under 2 hours, the third was at the beach and that was… pain 🙂



I’m quite often late to the party. This time for Strava. Many friends tried to convince me to join there but I just did this month. While I keep my Garmin data by myself, I opened my Strava profile and also added some images for my preferred routes. The Garmin Fenix 5S supports Strava live segments and that’s actually a fun way to battle oneself with other athletes for the fastest pace etc.

Anyway. Those numbers aren’t actually that important. I appreciate the measurements because it motivates me to get up and do something, but they are not something that defines me. And the same holds true for (our) passion for work. Reading this post on my IT blog probably means you’re yourself into computer science, programming etc. For whatever reason many of us kinda get sucked into this whole thing and spend more time than it’s healthy with IT. Myself: Not an exception. Shifting some habits did help me a lot, not only being fitter, but focussing more on work in the end.

While being outside and working out helps on clearing ones mind (at least with me), it also helps learning and reading about other things not in our profession. At the moment I am reading the German version of Ken Wilbers Integral Meditation: Mindfulness as a Way to Grow Up, Wake Up, and Show Up in Your Life and it gives me a nice mental shift. Last year I was occupied with the Black Swan by Nassim Taleb for some time.

In the end, it’s a bit of cognitive therapy: After realizing that I have to change habits to change my perception on a lot of things, one thing came to another and nearly 2 years after the first picture in this post has been taken, I feel a lot better and also happier. Not always, but often.

And if that all doesn’t change a bit, maybe just go outside and play ball:



Did you like this article? You can invite me on a coffee ☕️ if you like.

| Comments (1) »

28-Jun-18