Java: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
 
(23 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Other Stuff=
==Functional Interface==
A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit.
===Java Example===
Before Java 8, we had to create anonymous inner class objects or implement these interfaces.
<syntaxhighlight lang="java">
// Java program to demonstrate functional interface
 
class Test
{
    public static void main(String args[])
    {
        // create anonymous inner class object
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                System.out.println("New thread created");
            }
        }).start();
    }
}
</syntaxhighlight>
===Java Example===
And using lambda became
<syntaxhighlight lang="java">
// Java program to demonstrate Implementation of
// functional interface using lambda expressions
 
class Test
{
  public static void main(String args[])
  {
 
    // lambda expression to create the object
    new Thread(()->
      {System.out.println("New thread created");}).start();
  }
}
</syntaxhighlight>
===@FunctionalInterface Annotation===
@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation.
==JPA==
==JPA==
This is a rough overview of configuration JPA with hibernate.
This is a rough overview of configuration JPA with hibernate.
Line 4: Line 48:
===Pom.xml (Maven)===
===Pom.xml (Maven)===


MySQL
MySQL <br />
<syntaxhighlight lang="xml">
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
</dependency>
</syntaxhighlight>
 
Hibernate<br />
<syntaxhighlight lang="xml">
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>6.0.0.Alpha5</version>
    <type>pom</type>
</dependency>   
</syntaxhighlight>
 
Jta<br />
<syntaxhighlight lang="xml">
<!-- https://mvnrepository.com/artifact/javax.transaction/jta -->
<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>jta</artifactId>
    <version>1.1</version>
</dependency>
</syntaxhighlight>
 
Spring Orm/JDBC<br />
<syntaxhighlight lang="xml">
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>
 
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>
</syntaxhighlight>
 
===Persistence.xml===
 
<syntaxhighlight lang="xml">
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_2.xsd"
  version="2.2">
  <persistence-unit name="punit">
  </persistence-unit>
</persistence>
</syntaxhighlight>
 
===Web.xml===
 
Started by the container to listen for context events<br />
<syntaxhighlight lang="xml">
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classPath:/jpaContext.xml</param-value>
    </context-param>
   
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</syntaxhighlight>
 
===JpaContext.xml===
 
Initial context<br />
<syntaxhighlight lang="xml">
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx "
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
 
<context-annotation-config />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
 
</beans>
 
</syntaxhighlight>
 
Adding EntityManager and Properties<br />
<syntaxhighlight lang="xml">
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="perstistenceUnitName" value="punit"/>
<property name="dataSource" value="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"></property>
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDBDialect" />
<entry key="hibernate.hbm2ddl.auto" value="true" />
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
 
</syntaxhighlight>
 
Add Transaction Manager and Properties<br />
<syntaxhighlight lang="xml">
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</syntaxhighlight>
 
 
Add Data Source <br />
 
<syntaxhighlight lang="xml">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/fitnessTracker?autoReconnect=true"/>
<property name="username" value="noreal" />
<property name="password" value="noreal" />
</bean>
</syntaxhighlight>
 
===Annotations===
Generally three layers, controller, service and repository with a model
 
====Model====
Models have @Entity
 
<syntaxhighlight lang="java">
 
@Entity
@Table(name="Exercises")
 
public class Exercise {
@Id
@GeneratedValue
@Column(name="EXERCIDE_ID")
private Long id;
 
public Long getId() {
return id;
}
 
public void setId(Long id) {
this.id = id;
}
}
</syntaxhighlight>
 
====Service====
Service have @Service
 
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
  <dependency>
  @Service("exerciseService")
  <groupId>mysql</groupId>
public class ExerciseServiceImpl implements ExerciseService {
  <artifactId>mysql-connector-java</artifactId>
 
  <version>8.0.20</version>
@Autowired
  </dependency>
private ExerciseRepository exerciseRepository;
public List<Activity> findAllActivities() {
List<Activity> activities = new ArrayList<Activity>();
Activity run = new Activity();
run.setDesc("Run");
activities.add(run);
Activity bike = new Activity();
bike.setDesc("Bike");
activities.add(bike);
Activity swim = new Activity();
swim.setDesc("Swim");
activities.add(swim);
return activities;
}
 
@Transactional
public Exercise save(Exercise exercise) {
exercise = exerciseRepository.save(exercise);
return exercise;
}
  }
</syntaxhighlight>
</syntaxhighlight>
====Repository====
Repository have @Repository
<syntaxhighlight lang="java">
@Repository("exerciseRepository")
public class ExerciseRepositoryImpl implements ExerciseRepository {


Hibernate
@PersistenceContext
<dependency>
private EntityManager em;
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-entitymanager</artifactId>
public Exercise save(Exercise exercise) {
  <version>6.0.0.Alpha5</version>
  <type>pom</type>
em.persist(exercise);
  </dependency>
em.flush();
return exercise;
}
  }
</syntaxhighlight>


Jta
====Controller====
<dependency>
Controller have @Controller
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>


Spring Orm/JDBC
<syntaxhighlight lang="java">
<dependency>
@Controller
  <groupId>springframework</groupId>
  public class MinutesController {
  <artifactId>spring-orm</artifactId>
  <version>1.2.6</version>
  </dependency>


  <dependency>
@Autowired
  <groupId>org.springframework</groupId>
private ExerciseService exerciseService;
  <artifactId>spring-jdbc</artifactId>
  <version>5.2.6.RELEASE</version>
@RequestMapping(value = "/addMinutes", method = RequestMethod.GET)
  </dependency>
public String getMinutes(@ModelAttribute ("exercise") Exercise exercise) {
return "addMinutes";
}
@RequestMapping(value = "/addMinutes",  method = RequestMethod.POST)
public String addMinutes(@Valid @ModelAttribute ("exercise") Exercise exercise, HttpSession session, BindingResult result) {
System.out.println("exercise: " + exercise.getMinutes());
System.out.println("exercise activity: " + exercise.getActivity());
if(result.hasErrors()) {
return "addMinutes";
}
else
{
Goal goal = (Goal)session.getAttribute("goal");
exercise.setGoal(goal);
exercise = exerciseService.save(exercise);
}
return "addMinutes";
}
@RequestMapping(value = "/activities", method = RequestMethod.GET)
public @ResponseBody List<Activity> findAllActivities() {
return exerciseService.findAllActivities();
}
  }
</syntaxhighlight>

Latest revision as of 07:08, 26 April 2021

Other Stuff

Functional Interface

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit.

Java Example

Before Java 8, we had to create anonymous inner class objects or implement these interfaces.

 
// Java program to demonstrate functional interface
  
class Test
{
    public static void main(String args[])
    {
        // create anonymous inner class object
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                System.out.println("New thread created");
            }
        }).start();
    }
}

Java Example

And using lambda became

 
// Java program to demonstrate Implementation of
// functional interface using lambda expressions
  
class Test
{
  public static void main(String args[])
  {
  
    // lambda expression to create the object
    new Thread(()->
       {System.out.println("New thread created");}).start();
  }
}

@FunctionalInterface Annotation

@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation.

JPA

This is a rough overview of configuration JPA with hibernate.

Pom.xml (Maven)

MySQL

	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>8.0.20</version>
	</dependency>

Hibernate

	<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
	<dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate-entitymanager</artifactId>
    	<version>6.0.0.Alpha5</version>
    	<type>pom</type>
	</dependency>

Jta

	<!-- https://mvnrepository.com/artifact/javax.transaction/jta -->
	<dependency>
    	<groupId>javax.transaction</groupId>
    	<artifactId>jta</artifactId>
    	<version>1.1</version>
	</dependency>

Spring Orm/JDBC

	<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
	<dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-jdbc</artifactId>
    	<version>5.2.6.RELEASE</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
	<dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-orm</artifactId>
    	<version>5.2.6.RELEASE</version>
	</dependency>

Persistence.xml

 <persistence xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_2.xsd" 
  version="2.2">
  <persistence-unit name="punit">
  </persistence-unit>	
 </persistence>

Web.xml

Started by the container to listen for context events

    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classPath:/jpaContext.xml</param-value>
    </context-param>
    
    <listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

JpaContext.xml

Initial context

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:tx="http://www.springframework.org/schema/tx "
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<context-annotation-config />
	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

 </beans>

Adding EntityManager and Properties

	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="perstistenceUnitName" value="punit"/>
		<property name="dataSource" value="dataSource"/>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="true"></property>
			</bean>
		</property>
		
		<property name="jpaPropertyMap">
			<map>
				<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDBDialect" />
				<entry key="hibernate.hbm2ddl.auto" value="true" />
				<entry key="hibernate.format_sql" value="true" />
			</map>				
		</property>
	</bean>

Add Transaction Manager and Properties

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory"></property>
	</bean>
	
	<tx:annotation-driven transaction-manager="transactionManager" />


Add Data Source

	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/fitnessTracker?autoReconnect=true"/>
		<property name="username" value="noreal" />
		<property name="password" value="noreal" />
	</bean>

Annotations

Generally three layers, controller, service and repository with a model

Model

Models have @Entity

 @Entity
 @Table(name="Exercises")

 public class Exercise {
	
	@Id
	@GeneratedValue
	@Column(name="EXERCIDE_ID")
	private Long id;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
 }

Service

Service have @Service

 @Service("exerciseService")
 public class ExerciseServiceImpl implements ExerciseService {

	@Autowired
	private ExerciseRepository exerciseRepository; 
	
	public List<Activity> findAllActivities() {
		
		List<Activity> activities = new ArrayList<Activity>();
		
		Activity run = new Activity();
		run.setDesc("Run");
		activities.add(run);
		
		Activity bike = new Activity();
		bike.setDesc("Bike");
		activities.add(bike);
		
		Activity swim = new Activity();
		swim.setDesc("Swim");
		activities.add(swim);
		
		return activities;
	}

	@Transactional
	public Exercise save(Exercise exercise) {
		
		exercise = exerciseRepository.save(exercise);
		
		return exercise;
	}
 }

Repository

Repository have @Repository

 @Repository("exerciseRepository")
 public class ExerciseRepositoryImpl implements ExerciseRepository {

	@PersistenceContext
	private EntityManager em;
	
	public Exercise save(Exercise exercise) {
		
		em.persist(exercise);
		
		em.flush();
		
		return exercise;
	}
 }

Controller

Controller have @Controller

 @Controller
 public class MinutesController {

	@Autowired
	private ExerciseService exerciseService;
	
	@RequestMapping(value = "/addMinutes",  method = RequestMethod.GET)
	public String getMinutes(@ModelAttribute ("exercise") Exercise exercise) {
	
		return "addMinutes";
	}
	
	@RequestMapping(value = "/addMinutes",  method = RequestMethod.POST)
	public String addMinutes(@Valid @ModelAttribute ("exercise") Exercise exercise, HttpSession session, BindingResult result) {
		
		System.out.println("exercise: " + exercise.getMinutes());
		System.out.println("exercise activity: " + exercise.getActivity());
		
		if(result.hasErrors()) {
			return "addMinutes";
		}
		else
		{
			Goal goal = (Goal)session.getAttribute("goal");
			exercise.setGoal(goal);
			exercise = exerciseService.save(exercise);
		}
		return "addMinutes";
	}
	
	@RequestMapping(value = "/activities", method = RequestMethod.GET)
	public @ResponseBody List<Activity> findAllActivities() {
		return exerciseService.findAllActivities();
	}
 }