https://cbarkinozer.medium.com/i%CC%87leri-seviye-java-btk-akademi-kursu-notlar%C4%B1m-d87fa38c0769
I am sharing the notes I took while watching Advanced Java and Introduction to Java Programming courses.
Software: It is the computer-aided facilitation of people's daily life activities.
Spring Framework: Spring Framework is an application framework and IoC for the Java platform. Eclipse IDE is frequently preferred in institutions that use Spring.
Apache Tomcat: It is an open-source Java Servlet Container implementation developed by the Apache Software Foundation. It is a useful platform for developing and distributing web applications. It includes other necessary libraries such as Apache, MySQL, and Java.
Maven: It is a package manager developed by Apache that facilitates the process while developing a software project and controls the project and IDE dependencies.
Do not use the “if” command to return values that are alternatives to each other. You can use it for value comparison purposes.
Spring IOC and Dependency Injection:
JSP (JavaServer Pages): It is one of the Java technologies and is used to create dynamic Web pages with languages such as HTML and XML. The creation of the page occurs at the request of a Web client.
Java Beans: In Java-based programs, JavaBeans are classes that encapsulate many objects into a single object. It has a serializable, zero-variable constructor and allows access to properties using getter and setter methods.
Apache XMLBeans: XMLBeans is a Java-XML binding framework that is part of the Apache Software Foundation XML project.
“99% of the industry uses constructor injection” – Engin DemiroÄŸ
It can be done from the injection properties file. For example:
<context:property-placeholder location=”classpath:values.properties”/>
It can also be done in the form of injection and annotation. In the format “@Component(“database”)”.
We can also perform injection via class without using XML.
We create AnnotationConfigApplicationContext and send the IocConfig class into it.
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IocConfig.class);
In the IocConfig class, we inject by adding @Configuration and @ComponentScan(“packet_name”) before the class codes and after the import.
We write the following code following the @Bean notation in the IocConfig class:
ICustomerBal database(){
return new MsSqlCustomerBranch();
}
@PropertySource(“classpath:values.properties”) : Tells the location of the file.
@Value(“${database.connectionString}”) Learns where to read the value.
Hibernate ORM:
It associates classes with tables in the database. It is ORM that dominates the industry. After the files are manually added to the lib file, they must be added to the file path from the project settings.
The information that must be included in the configuration XML file for Hibernate are drive_class, url, username, password, pool_size, current_session_context_class, show_sql, dialect information.
@Entity notation indicates the database object, we import “javax.persistence”.
@Table(names="city") points to the database table.
We map the name of each Entity field by entering @Column(name=”name”). With @Id we specify the primary key (PK/primary key) of the table.
Database connection (DBConnection) is called session in Java language. SessionFactory produces sessions.
SessionFactory creation example: “SessionFactory factory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(City.class).buildSessionFactory();” it is like this.
“configure” gets our configuration file. “addAnnotatedClass” gives us which class we will create sessionFactory for.
Example of running a query with hibernate (non-object oriented method):
try{
session.beginTransaction();
List<City> cities = session.createQuery(“from City c where c.countryCode=’TUR’ ”).getResultList();
for(City city:cities){
System.out.println(city.getName());
}
Session.getTransaction().commit();
}
The “list()” method has been deprecated, and “getResultList()” is used instead.
HQL (hibernate query language): An object-oriented query language similar to SQL, but instead of working on tables and columns, it works with persistent objects and their properties. HQL queries are translated into traditional SQL queries by Hibernate, which in turn performs actions on the database. We will soon learn how to perform CRUD (create, read, update, delete) operations in an object-oriented way, with ORM.
Example of insertion:
City city new = City();
city.setName(“Duzce 10”);
city.setCountryCode(“TUR”);
city.setDistrict(“Black Sea”);
city.setPopulation(100000);
session.save(city);
session.getTransaction().commit();
Update process example:
City city = session.get(City.class,4086);
City.setPopulation(110000);
Session.save(city);
Session.getTransaction().commit();
Example of deletion operation:
City city = session.get(City.class,4086);
Session.delete(city);
Session.getTransaction().commit();
Maven:
It is a project management tool. We can manage jar files. kl
Asik creates project templates (provides us with standards). It offers Build, or version tracking system, service through configuration management tools.
We can look at the “mvnrepository.com” site to search whether a framework is available in Maven. We can add the package by copying the XML code from this site and pasting it into the POM file in Maven.
POM: It is an XML file used in Maven to set up a project and contains information about the project and its configuration.
The "group id" required when creating a project is the name of the company/team that wrote the program. “Artifact id” is the name of the project.
To indicate to Maven the JDK version used:
to the “pom.xml” file
<maven.compiler.target>1.11(your_JDK_version)</maven.compiler.target>
<maven.compiler.source>1.11(your_JDK_version)</maven.compiler.source >
lines are added.
When you add a dependency (project) to your project, packages are downloaded from Maven servers to your local Maven files. This way your app is using that package from your local Maven files.
For example, when we want to add Hibernate Core, the information we will add to our pom.xml file is as follows:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
You can access this information from mvnrepository.
Spring Boot:
It is an open-source application development framework developed for Java.
The word boot comes from bootstrap (to start). It is very popular.
The basic features of Spring Framework can be used by any Java application.
It can also be used to develop web applications on the Java Enterprise platform with its plug-ins.
Its main purpose is to reduce overall development time and increase efficiency by having a default setup for unit and integration tests.
If you want to get started with your Java application quickly, you can easily accept all defaults and avoid XML configuration altogether.
We can download our customized Spring Boot file from start.spring.io.
Two notes independent of the course topic:
1) Gradle: Gradle is a build automation tool for multilingual software development. Controls the development process in tasks from compilation and packaging to testing, deployment, and release. Supported languages include Java, C/C++ and JavaScript.
2) .io extension: This domain name for Britain and the Indian Ocean territories has become popular because it means input/output in computer jargon. For this reason, technology companies and new ventures use it.
Spring Boot comes with “mvnw” and “mvnw.cmd” files. These files enable Maven usage for non-Maven environments.
Rest and Java are referred to as backend. The backend sends data to the frontend. This frontend can be Jquery, Angular, React, Vue.js and Flutter (on mobile).
REST API:
REST (Representational State Transfer) is an abbreviation that means Representational State Transfer. API (application programming interface) means application programming interface.
REST is a distributed system that uses Web protocols and technologies. Systems that provide REST principles are called RESTful. It is a service structure that aims to establish fast and easy communication between the client and the server. With the increase in mobile usage after 2015, it took the throne of SOAP. It enables communication between applications by carrying XML or JSON files between the client and server. Nowadays they are not XML, they are in JSON format.
SOAP (Simple Object Access Protocol): It is a messaging protocol used for information exchange, configured for web service applications in computer networks.
Restful API writing:
We add the "@RestController" annotation to our class, which we will import from springframework.web.bind.annotation.
“@GetMapping(“/”)” notation. It means run this method on the main request page of our application server.
Note: Spring Boot contains Apache Tomcat and requests the “local:8080” port. If you have previously installed Apache Tomcat, it will also keep local:8080 and these will conflict and cause you to receive an error. In this case, disabling the Tomcat you installed from “services.msc” will solve the problem. Additionally, any changes you make while your project is running will not be reflected on your web page. To do this, you need to stop and run it again after making changes.
As soon as we make changes, we add the spring-boot-devtools dependency to the pom.xml file to go live.
JPA (Java Persistence API): It is used to store relational data with Java classes. It allows data to be saved after the application runs and finishes. SQL queries are included in JPA. We gain the opportunity to work directly on objects instead of SQL commands. We must add the dependency code with spring-boot-starter-data-jpa artifactId to the pom.xml file. It emerged like ORM and later became a standard.
application properties file configuration:
Spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
Spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
Spring.datasource.url=jdbc:mysql://localhost:3306/world?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
Spring.datasource.username=root
spring.datasource.password=12345
super() method: “An object belonging to the superclass replaces the constructor. If overloaded constructors are defined in the parent class, the parameters used determine which one to call. Because the Java compiler distinguishes overloaded functions with the help of their parameters.”[3]
The “@Autowired” notation allows you to implicitly inject object dependency. It uses setter or constructor injection internally. “Autowiring” cannot be used to inject “primitive” and “string” values. It works by reference only.
unwrap() method: Returns an object that implements the given interface to allow access to non-standard methods or standard methods not exposed by the proxy. If the receiver implements the interface, the result is a proxy for the receiver or receiver. When an error occurs, it throws a "SQLException" error.
@Transactional: Enables automatic use of session opening and closing codes. It is AOP (aspect oriented programming) method.
@Service: It means this is a business layer.
@RestController: This is a rest api controller.
@Repository: This means I am using Repository. When we use something other than Hibernate, we need to cut and paste this notation there to point to it.
@PostMapping(“/update”): This is the notation used for post operations.
@GetMapping(“/cities/{id}”): {id} allows us to give parameters dynamically.
@RequestBody: Indicates that the method parameter should be bound to the body of the http request.
@PathVariable: We use it to specify the path of our API.
Postman: A popular API client that makes it easy for developers to create, share, test and document APIs. It allows users to create simple and complex HTTP/s requests, save them, and read their responses. As a result, the job can be done more efficiently and less tiringly.
My introductory notes to Java Programming:
Note: I only noted what I didn't know.
public int sum(int… arguments){}
In the parameters section, three dots are used to mean that I can send more than one parameter of the same type. The arguments are converted to an array in the background and sent.
Value variable types are kept on the stack. Reference variable types represent the heap. Due to this indication, abnormal results may be obtained in some cases. Setting reference variables equal to each other or new is the main source of creating these anomalies.
In Java, if there is a "static" keyword in front of the function name, an instance of the object is created once and everyone uses that instance. Thus, we can access and use functions by putting a period at the end of the class name. That instance is not refreshed and is not thrown from memory until the application stops, so we cannot use it for every function. We prefer it for auxiliary, use-and-leave type structures.
Constructor blocks do not work in Java (they work in C#). Static constructor blocks are used in Java. for example: “static{}”.
Inner classes do not comply with SOLID principles, so they should not be done.
When using Java professionally, we use type-safe ArrayLists (java.util.ArrayList) for arrays (ArrayLists use all data types together, which can cause problems). ArrayList class has ready-made functions such as insertion and deletion. Using them is both safer and more comfortable. “ArrayList<String> = new ArrayList<String>();” is a string type safe ArrayList.
HashMap is like an array, but it saves information as key and data. For example: “HashMap<String,String> dictionary= new HashMap<String,String>();” .
Exception and Error are two different things. Excepiton are things we can keep under control with codes. Errors for Java: AWTError, AssertionError, IOError, ExceptionInInitializeError and VirtualMachineError(OutOfMemory, StackOverflow). The remaining errors are exceptions.
Difference between exception and error
All exception types are inherited from the exception interface.
Generics:
It allows us to create gender-specific classes. It is also used when creating general interfaces to avoid constantly creating interfaces of the same type.
For example: “public class MyClass<T>{public void Add(T value){}}”.
Generic constraint:
For example, if you defined a list of string type, it would blush when you gave it an int. When you use a generalizer, he will get angry if you do not give it in the Car class type. The inheritance of the type you specify here can also pass the check without any problems and do not receive any errors, but sometimes this does not work for you. For example, it makes sense to derive the ATV class from car.
You think about it and do it that way, but it can be used in the generic class where it should not be. To prevent this (may vary depending on the language), you can specify your rules where the definition is made and according to those rules, you can only accept the types you want.
Example: “public class MyClass<T extends IEntity>{public void Add(T value){}}”.
Generalizing methods are not used as frequently as generalizing classes.
For example:“public <T> void Add(T entity){}”.
Generalizer constrained generalizer method: “public <T extends IEntity> void Add(T entity){}”.
Threading:
It is the execution line in which a program orders actions. In multi-threading structures, the program continues the work to be done simultaneously from several different branches.
It is more difficult to debug and design, so it is tried to be avoided as much as possible.
JDBC:
It is the package used to connect to the database. In professional transactions, these tasks are done with ORM. “DriverManager.getConneciton();”
SQL queries that change basic tables: insert, delete, update.
“insert into(Name, CountryCode, District, Population) values(‘Düzce’,’TUR’,’Düzce’,5000)”
Since the update process may be dangerous, it will warn you to review it. You can confirm this with the command below.
“set SQL_SAFE_UPDATES=0”
“update city set Population = 60000 where name=’Düzce’ ”
“delete from city where id=4080”
Transacting with ID is common.
We prefer to implement database connection operations in a single class. This class contains the username, password and database url and performs database connection operations.
Do not forget to use the database connection process within the try-catch structure.
We keep the answer received as a result of the query in a list of database object type.
“
connection= helper.getConnection();
String sql = “insert into city(Name,District,Population) value(?,?,?)”;
Statement=connection.prepareStatement(sql);
Statement.setString(1,”Düzce”);
Statement.setString(2,”Turkey”);
Statement.setString(3,70000);
int result= statement.executeUpdate();
”
Swing is used to implement desktop applications with Java. Swing is best used in the NetBeans IDE.
A class can inherit many interfaces (implement keyword), but a class can inherit only one class (or abstract class) (extends keyword).
An interface in Java has no constructor because all data members in interfaces are public static final by default, they are constant.
When pointing to elements of arrays, the pointer starts from zero. Because of the n,n+1 mentality in mathematics. However, when we use “.length()” and look at the length, it will give the result with +1 added.
Classes have definition fields. Only the following can be defined within a class: variable, method, class (not recommended). For example, we cannot write an if-else block within the class without being inside the method.
Resources:
[1]BTK Academy - Advanced Java Course
[2]Wikipedia
[3]Basket University - Java course
[http://www.baskent.edu.tr/~tkaracay/etudio/ders/prg/java/ch15/]
[4]BTK Academy- Introduction to Programming with Java
0 Comments