Spring/boot Flashcards
run java application from command line with maven
mvn clean compile exec:java
how to view the final created pom file that contains the pom and any parent poms and generated config
mvn help:effective-pom
can you have an empty dependencies body in the pom.xml?
yes
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test
I didn’t have a class with ‘@SpringBootApplication’ annotated before it
the proper way to run from command line a pom.xml file downloaded from spring initializr
./mvnw spring-boot:run or mvn spring-boot:run
if you want to run a freshly download spring initialzr project using mvn clean compile exec:java what do you need to do?
mvn -X exec:java -Dstart-class=com.example.demo.DemoApplication
@RestController annotation
marks the class as a controller where every method returns a domain object instead of a view. It is shorthand for including both @Controller and @ResponseBody.
@SpringBootApplication is a convenience annotation that adds:
@Configuration, @EnableAutoConfiguration, @ComponentScan
@Configuration,
Tags the class as a source of bean definitions for the application context.
the 2 things to run a project with gradle
1) you have to have set it up with a build.gradle file, e.g. thru the Spring Initializer 2) use ./gradlew bootRun
@EnableAutoConfiguration,
Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.
@ComponentScan
Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.
JavaBeans
classes that encapsulate many objects into a single object (the bean)
beans in Spring
The objects that form the backbone of your application and that are managed by the Spring IoC container [ https://www.tutorialspoint.com/spring/spring_bean_definition.htm]
How to build jar file using gradle
./gradlew build
run spring with gradle on another port - method 1
add following to src/main/java/resources/application.yml: server:\nport: 8081
run spring with gradle on another port - method 2
add following to src/main/java/resources/application.properties: server.port=8081
POJO
Plain Old Java Object
Baeldung’s definition of IoC
is a process in which an object defines its dependencies without creating them
In IoC, objects delegate the job of constructing dependencies to
an IoC container
JPA
Java Persistence API. Mechanism to interface with databases
how to create a new Spring project
spring init –dependencies=web,data-jpa my-project
how to create a new Spring project with gradle
spring init –dependencies=web,data-jpa –build=gradle my-project
@Data annotation
from “import lombok.Data;” @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together: In other words, @Data generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans: getters for all fields, setters for all non-final fields, and appropriate toString, equals and hashCode implementations that involve the fields of the class, and a constructor that initializes all final fields, as well as all non-final fields with no initializer that have been marked with @NonNull, in order to ensure the field is never null.
why wasn’t my Junit test running?
I didn’t have the @Test annotation beforehand
Why weren’t my console logs working in my unit test?
I needed to add the following to the bottom of my build.gradle:
test {
testLogging.showStandardStreams = true
}
basic Springboot injection layout example
1) have a class called Company annotated with @Component 2) add a property in the class private Address address
. No need for an annotation 3) Create the Address class. no need for annotations 4) create a config class wrapped with @Configuration, @ComponentScan(basePackageClasses=Company.class),
@ComponentScan ensures that the classes decorated with @Component are _____
are found and registered as Spring beans.
in my UserPool class why was it that I wasn’t able to dependency inject a property using the @Value annotation?
because I had also defined a constructor, and i think particularly because the constructor had properties that had no dependency injection definitions, and the DI system didn’t know how to behave in context of this constructor
what is hibernate?
an ORM
HQL
Hibernate Query Language
JPQL
Java Persistence Query Language
JPQL vs HQL
JPQL is a subset of HQL
what does JPA do?
map your application classes to database tables
what handles all the interactions with a database?
EntityManager
Hibernate vs JPA
JPA defines the specification. Hibernate is one of the implementations
how do i access the entityManager from withinside a Service class?
add a property like @PersistenceContext private EntityManager entityManager;
EntityManager is part of the ___ API?
Java Persistence
what does JPA do?
implement the programming interfaces and lifecycle rules determined by the JPA specification
what are the two types of EntityManager?
Container-Managed and Application Managed
what caused the could not initialize proxy [com.sri.api.entities.Organization#15e83f0e-eda5-443b-b1c0-386cadf19fbd] - no Session bug upon Spine login?
removing the @Transactional flag from login(..) and adding it for each of the child methods completeAnyPendingTrainingIdentityVerification and markUserRolesPendingApprovalForRolesWithAllTrainingsComplete. Why? I’m not sure
what caused this bug upon login? “Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead”
trying to use persist on entityManager (which was injected with @PersistenceContext) inside of a method that was a callee of userService.login method (which was wrapped with @Transactional). using an em created from an entityManageFactory does not work either
purpose of transaction
if writing code that interfaces with the database, the later parts interacting with the database won’t be written if the first parts failed
SPI
service provider interface
JNDI
Java Naming and Directory Interface
can you call an @transactional method from inside of a non @transactional method?
only if the called method is in a different bean
another consequence of adding @transactioal to a method
spring will handle Hibernate sessions
what does it mean for spring to handle hibernate sessions
it will let you do something like the following after having obtained a user from the userRepository: user.getOrganization().getStage(). without it managing the sessions, the db session would be closed and .getOrganization() would be null, as that is lazily loaded.
what happened when i tried manually injecting in an entityManager in a bean being called by another bean’s method that was marked by @transactional?
“Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead”
cause of “could not initialize proxy [com.sri.api.entities.Organization#15e83f0e-eda5-443b-b1c0-386cadf19fbd] - no Session”
a user.getOrg().something call was inside of a method that was not wrapped with @transactional
if I try to access a lazily loaded value inside c2.a(), which is in turn called by c1.a(), and c1.a() is marked @Transactional(), does c2.a() need to be marked @Transactional()?
no
if I try to access a lazily loaded value inside c2.b(), which is in turn called by c2.a(), which is in turn called by c1.a(), and c1.a() is marked @Transactional(), what methods of c2 need to be labeled @Transactional()
neither
why was our agent.getOrganization() call returning null properties in our debugger?
it was returning an object of instance Organization$HibernateProxy, which by default will set each property equal to null upon inspection, but upon actual evaluation of a property of that proxy object, it will return the actual value from the database - e.g. agent.getOrganization().getGuid() will return a value of the form “15e83f0e-eda5-443b-b1c0-386cadf19fbd”
What was the original scenario in which we had to learn about transactions?
in userController.login() we had subroutine a() and b(). a set data in the db that b then had to access. b wasn’t able to access any of that new data because the transaction a (and b) was a part of hadn’t finished yet. To solve this we put a and b in separate classes from the userController, as in A.a() and B.b() and marked a and b both transactional, and userController.login() not transactional. this let a and b both operate in different transactions, letting a save the data to the db before b started accessing the db.
What happens if @transactional A.a() calls B.b() and B.b() is marked Transactional as well()
not sure yet. [ do both a and b share the same transaction?? ] [ do both a and b share the same hibernate session?? are these separate questions ? ]]
What happens if you call @Transactional A.b() from @Transactional A.a() and a() was the first method in the call chain marked @Transactional
If you call a method with a @Transactional annotation from a method with @Transactional within the same instance, then the called methods transactional behavior will not have any impact on the transaction. But the transaction+session will still continue, as if the child method didn’t even have @Transactional on it. https://stackoverflow.com/a/6222624/2453293
What happens if you call @Transactional A.b() from @Transactional A.a() and actually the caller of a() was marked @Transactional too
pretty sure A.b() is treated as if there was no @Transactional tag, because of how AOP proxies behave in Spring [ https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#tx-decl-explained, https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies]
What happens if you call [not marked @Transitional] A.b() from @Transactional A.a() and a() was the first method in the call chain marked @Transactional
When you call a method without @Transactional within a transaction block, the parent transaction will continue to the new method. It will use the same connection from the parent method(with @Transactional) and any exception caused in the called method(without @Transactional will cause the transaction to rollback as configured in the transaction definition. [ https://stackoverflow.com/questions/6222600/transactional-method-calling-another-method-without-transactional-anotation/6222624#6222624].
I’m guessing this applies for methods called on other instances, too, but not sure.
can you you have an inner method in the same bean use a different transaction as that of an outer method in the same bean?
yes.by doing @Transactional(propagation=Propagation.REQUIRES_NEW) on the inner method https://stackoverflow.com/a/55540186/2453293
can you you have an inner method in the same bean use a different transaction as that of an outer method in the same bean?
yes.by doing @Transactional(propagation=Propagation.REQUIRES_NEW) on the inner method https://stackoverflow.com/a/55540186/2453293
@Transaction default Propagation behavior
Required
JDO
Java Data Object
CGLIB
Code Generation Library aka “Byte Code Generation Library”
Byte Code Generation Library
a high level API to generate and transform Java byte code. It is used by AOP, testing, data access frameworks to generate to generate dynamic proxy objects and intercept field access
What does calling a method on a transactional proxy look like?
Caller -> AOP proxy -> Transactional Advisor -> Custom Advisors -> Target Method