J Notes
J Notes
J Notes
https://thoughts-on-java.org/tutorials/
The java string intern() method returns the interned string. It returns the
canonical representation of string.
VirtualMachineError or StackOverflowError
throwable
- error
- exception
- checked (compile time)
- unchecked (runtime)
checked exception
-> compile time exception
unchecked exception
-> runtime exception
Primetive vs wrapper
Caution is required when using the ternary operator with boxed types and null. From
the language specification:
If one of the second and third operands is of primitive type T, and the type of the
other is the result of applying boxing conversion to T, then the type of the
conditional expression is T.
- for wrapper always use .equals() method to compare value otherwise always false
as it is object.
https://dzone.com/articles/how-does-spring-transactional
https://docs.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html
datatypes
primitive vs wrapper
typeconverstion
string operation
.contains("")
.compareTo("") lexicographically compare
.equal
.substring(start, end)
date operation
autoboxing
marshaling
seralizing
collections
- list, set, map
- basics
- operations
An abstract class cannot be instantiated directly, i.e. object of such class cannot
be created directly using new keyword. An abstract class can be instantiated either
by concrete subclass, or by defining all the abstract method along with the new
statement. A concrete class can be instantiated directly, using a new keyword.
JPA
- hibernet
--> all toOne are egar
--> all toMany are lazy by default
@OneToOne
Use @PrimaryKeyJoinColumn for associated entities sharing the same
primary key.
Use @JoinColumn & @OneToOne mappedBy attribute when foreign key is held
by one of the entities.
Use @JoinTable and mappedBy entities linked through an association
table.
Persist two entities with shared key using @MapsId
@ManyToOne
Use @JoinColumn when foreign key is held by one of the entities.
Use @JoinTable for entities linked through an association table.
@OneToMany
Use mappedBy attribute for bi-directional associations with ManyToOne
being the owner.
OneToMany being the owner or unidirectional with foreign key - try to
avoid such associations but can be achieved with @JoinColumn
@JoinTable for Unidirectional with association table
@ManyToMany
Use @JoinTable for entities linked through an association table.
Use mappedBy attribute for bi-directional association.
Jdbc
logs
spring boot
- anotations
- transactiona management
-
memeory management
deployment
kubernatice
kibanna
https://thoughts-on-java.org/5-common-hibernate-mistakes-that-cause-dozens-of-
unexpected-queries/
===> all many to one are egar by default so need to mark as lazy when required
===> for lazy association, runs extra quries so use LEFT JOIN FETCH relation
instead when required
===> for list relation all elements are removed & and addded for any changes, so
mark attribute are Set not List
===> removing child eith CascadeType.Remove maked individual quries
===> updating and removing in bulk using In makes individual quries
em.flush();
em.clear();
https://www.baeldung.com/spring-core-annotations
@Autowired
@Bean
@Bean
Engine engine() {
return new Engine();
}
@Qualifier
@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
this.vehicle = vehicle;
}
@Required
void setColor(String color) {
this.color = color;
}
<bean class="com.baeldung.annotations.Bike">
<property name="color" value="green" />
</bean>
@DependsOn("engine")
class Car implements Vehicle {}
@Configuration
@Lazy
class VehicleFactoryConfig {
@Bean
@Lazy(false)
Engine engine() {
return new Engine();
}
}
@Primary
class Car implements Vehicle {}
@Component
@Scope("prototype")
class Engine {}
@Profile("sportDay")
class Bike implements Vehicle {}
@Import(VehiclePartSupplier.class)
class VehicleFactoryConfig {}
https://www.baeldung.com/spring-mvc-annotations
WEB anotaions
@RequestMapping
path, or its aliases, name, and value: which URL the method is mapped to
method: compatible HTTP methods
params: filters requests based on presence, absence, or value of HTTP
parameters
headers: filters requests based on presence, absence, or value of HTTP
headers
consumes: which media types the method can consume in the HTTP request body
produces: which media types the method can produce in the HTTP response body
@PostMapping("/save")
void saveVehicle(@RequestBody Vehicle vehicle) {
@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable("id") long id) {
// ...
}
@RequestMapping
Vehicle getVehicleByParam(@RequestParam("id") long id) {
// ...
}
If we mark a request handler method with @ResponseBody, Spring treats the result of
the method as the response itself:
@ResponseBody
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}
With this annotation, we can declare a custom error handler method. Spring calls
this method when a request handler method throws any of the specified exceptions.
@ExceptionHandler(IllegalArgumentException.class)
void onIllegalArgumentException(IllegalArgumentException exception) {
// ...
}
We can specify the desired HTTP status of the response if we annotate a request
handler method with this annotation. We can declare the status code with the code
argument, or its alias, the value argument
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
void onIllegalArgumentException(IllegalArgumentException exception) {
// ...
}
@Controller
@ModelAttribute
With this annotation we can access elements that are already in the model of an
MVC @Controller, by providing the model key:
@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicleInModel) {
// ...
}
https://www.baeldung.com/spring-boot-annotations
@SpringBootApplication
@SpringBootApplication encapsulates @Configuration, @EnableAutoConfiguration,
and @ComponentScan annotations with their default attributes.
Using these conditions, Spring will only use the marked auto-configuration
bean if the class in the annotation’s argument is present/absent:
@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoconfiguration {
//...
}
@Bean
@ConditionalOnProperty(
name = "usemysql",
havingValue = "local"
)
DataSource dataSource() {
// ...
}
@ConditionalOnResource
@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties additionalProperties() {
// ...
}
@ConditionalOnWebApplication
@Bean
@ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
DataSource dataSource() {
// ...
}
@Conditional(HibernateCondition.class)
Properties additionalProperties() {
//...
}
https://www.baeldung.com/spring-data-annotations
@Transactional
want to configure the transactional behavior of a method
@Transactional
void pay() {}
@NoRepositoryBean
interface MyUtilityRepository<T, ID extends Serializable> extends CrudRepository<T,
ID> {
Optional<T> findById(ID id);
}
@Id
Long id;
@Transient
int age;
With these annotations, we can audit our model classes: Spring automatically
populates the annotated fields with the principal who created the object, last
modified it, and the date of creation, and last modification:
@CreatedBy
User creator;
@LastModifiedBy
User modifier;
@CreatedDate
Date createdAt;
@LastModifiedDate
Date modifiedAt;
We can configure the lock mode when we execute a repository query method
@Lock(LockModeType.NONE)
@Query("SELECT COUNT(*) FROM Person p")
long getPersonCount();
READ
WRITE
OPTIMISTIC
OPTIMISTIC_FORCE_INCREMENT
PESSIMISTIC_READ
PESSIMISTIC_WRITE
PESSIMISTIC_FORCE_INCREMENT
NONE
userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
When the @Query annotation uses native SQL, then it’s not possible to define
a Sort.
https://www.baeldung.com/spring-data-jpa-query
https://www.baeldung.com/spring-scheduling-annotations
When single-threaded execution isn’t enough, we can use annotations from the
org.springframework.scheduling.annotation package.
singleton
default
@Bean
@Scope("singleton")
prototype
A bean with prototype scope will return a different instance every time it is
requested from the
As mentioned, there are four additional scopes that are only available in a
web-aware application context
request
session
application
websocket
The request scope creates a bean instance for a single HTTP request while session
scope creates for an HTTP Session.
The application scope creates the bean instance for the lifecycle a ServletContext
and the websocket scope creates it for a particular WebSocket session.
byte b = 10;
// Using b = b+1
b = b + 1;
System.out.println(b);
/* Using typecasting will work
b=(byte)b+1;
System.out.println(b);*/
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
https://www.geeksforgeeks.org/multithreading-in-java/
3) By anonymous object:
new Employee();
Note: The Garbage collector of JVM collects only those objects that are
created by new keyword. So if you have created any object without new, you can use
finalize method to perform cleanup processing (destroying remaining objects).
Java Runtime class is used to interact with java runtime environment. Java Runtime
class provides methods to execute a process, invoke GC, get total and free memory
etc. There is only one instance of java.lang.Runtime class is available for one
java application.
####################################################
java 8
- interface can have static & default method implementations
- in case, where class implements 2 interface with same name, the class must
provide its own implementations
@NonfunctionalInterface
for interface having only one abstract method , similar to @Override anotations
@NonNullApi: Used on the package level to declare that the default behavior for
parameters and return values is to not accept or produce null values.
@org.springframework.lang.NonNullApi
package com.acme;
@NonNull: Used on a parameter or return value that must not be null (not needed on
a parameter and return value where @NonNullApi applies).
@Nullable
User findByEmailAddress(@Nullable EmailAddress emailAdress);
Returns null when the query executed does not produce a result. Also
accepts null as the value for emailAddress
User findFirstByOrderByLastnameAsc();
User findTopByOrderByAgeDesc();
Named Queries
@Entity
@NamedQuery(name = "User.findByEmailAddress",
query = "select u from User u where u.emailAddress = ?1")
public class User {
Nativ query
public interface UserRepository extends JpaRepository<User, Long> {
named parameter
https://codepumpkin.com/hashset-internal-implementation/
========================================
Spring Annotations
==
org.springframework.context.annotation
public @interface Bean
@Bean
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;
}
@Bean({"b1", "b2"}) // bean available as 'b1' and 'b2', but not 'myBean'
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;
}
Profile, Scope, Lazy, DependsOn, Primary, Order
Note that the @Bean annotation does not provide attributes for profile,
scope, lazy, depends-on or primary. Rather, it should be used in conjunction with
@Scope, @Lazy, @DependsOn and @Primary annotations to declare those semantics. For
example:
@Bean
@Profile("production")
@Scope("prototype")
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;
}
@Lazy only has an actual effect in case of the default singleton scope.
@DependsOn enforces the creation of specific other beans before this bean
will be created, in addition to any dependencies that the bean expressed through
direct references, which is typically helpful for singleton startup.
@Primary is a mechanism to resolve ambiguity at the injection point level if
a single target component needs to be injected but several beans match by type.
Additionally, @Bean methods may also declare qualifier annotations and @Order
values, to be taken into account during injection point resolution just like
corresponding annotations on the corresponding component classes but potentially
being very individual per bean definition (in case of multiple definitions with the
same bean class). Qualifiers narrow the set of candidates after the initial type
match; order values determine the order of resolved elements in case of collection
injection points (with several target beans matching by type and qualifier).
NOTE: @Order values may influence priorities at injection points, but please
be aware that they do not influence singleton startup order which is an orthogonal
concern determined by dependency relationships and @DependsOn declarations as
mentioned above. Also, Priority is not available at this level since it cannot be
declared on methods; its semantics can be modeled through @Order values in
combination with @Primary on a single bean per type.
@Bean methods may also be declared within classes that are not annotated with
@Configuration. For example, bean methods may be declared in a @Component class or
even in a plain old class. In such cases, a @Bean method will get processed in a
so-called 'lite' mode.
, 'inter-bean references' are not supported in lite mode. Instead, when one
@Bean-method invokes another @Bean-method in lite mode, the invocation is a
standard Java method invocation; Spring does not intercept the invocation via a
CGLIB proxy. This is analogous to inter-@Transactional method calls where in proxy
mode, Spring does not intercept the invocation — Spring does so only in AspectJ
mode.
==
@Override Why?
Use it every time you override a method for two benefits. Do it so that you can
take advantage of the compiler checking to make sure you actually are overriding a
method when you think you are. This way, if you make a common mistake of
misspelling a method name or not correctly matching the parameters, you will be
warned that you method does not actually override as you think it does. Secondly,
it makes your code easier to understand because it is more obvious when methods are
overwritten.
==
==
Array list internally uses array
The default initial capacity of an ArrayList is pretty small (10 from Java 1.4 -
1.8). But since the underlying implementation is an array, the array must be
resized if you add a lot of elements. To avoid the high cost of resizing when you
know you're going to add a lot of elements, construct the ArrayList with a higher
initial capacity.
==
transient is a Java keyword which marks a member variable not to be serialized when
it is persisted to streams of bytes
@DoNotSerialize
==
Hasset internally uses hasmap, and puts values as keys of hasmap. so doen't allow
duplicate values. And for Value field it does set dummy value object with "PRESENT"
value
==
Generally Arralylist is prefered over linked list because it uses more memory to
store 2 additional addresses,
==
jps - the Java Process Status Application The tool is limited to reporting
information on JVMs for which it has the access permissions.
==
jstat -gc -h5 -t 14984 2500 30
jstat -gcutil 21891 250 7
3 types of annotations
- marker
just mark, do not accept any value @Override
- single value
single member and it is mandatory
- full
Starting with J2SE 5.0, you deprecate a class, method, or field by using the
@Deprecated annotation. Additionally, you can use the @deprecated Javadoc tag tell
developers what to use instead.
You can use the @deprecated tag to make Javadoc show a program element as
deprecated. The @deprecated tag must be followed by a space or newline. In the
paragraph following the @deprecated tag, explain why the item has been deprecated
and suggest what to use instead.
/**
* Delete multiple items from the list.
*
* @deprecated Not for public use.
* This method is expected to be retained only as a package
* private method. Replaced by
* {@link #remove(int)} and {@link #removeAll()}
*/
@Deprecated public synchronized void delItems(int start, int end) {
...
}
spring MVC
@RequestMapping("/spring-web/{symbolicName:[a-z-]}-{version:\\d\\.\\d\\.\\d}
{extension:\\.[a-z]}")
public void handle(@PathVariable String version, @PathVariable String
extension) {
// ...
}
}
// GET /pets/42;q=11;r=22
// petId == 42
// q == 11