Hello everyone. In this article, we will see the differences between JPA, Hibernate, and Spring Data JPA.

ORM Frameworks

ORM Stands for Object-Relational Mapping that maps the data in the database to the Java Class which is called an Entity. Not only that, but ORM also preserves the relationship between the tables at the Entity level.

There are many ORM frameworks in the market and the famous ones for Java are

  1. Hibernate
  2. EclipseLink
  3. iBATIS
 

What is Hibernate?

As we all know, Hibernate is an ORM framework that sits between the application and the database. Before Hibernate, developers used to write queries using JDBC and retrieve the data and manually set it to the DTO Objects and send it to the Front End. This was time-consuming and painful.

So Hibernate is a framework in the ORM layer that maps the relational data to the Java Objects. It also provides an abstraction to the developers so that they don't need to worry about the data source. It also provides configuration options to configure the data store and developers can also write queries with Hibernate

Features of Hibernate

1. Light Weight

2. Open Source

3. ORM (Object Relation Mapping)

4. High Performance

5. HQL (Hibernate Query Language)

6. Caching

7. Auto-Generation

8. Scalability

9. Lazy Loading

10. Database Independent

Lets us see only a few important features below

 

Hibernate Query Language (HQL)

SQL is low-level programming where developers have to query for the database columns in a database table. But HQL is simplified for developers in such a way that the Java class names and attributes are used in the query. Internally, hibernate converts HQL into SQL and executes it in the database.

Hibernate also supports native SQL queries along with the HQL but it is recommended to use HQL as it is independent of the underlying database. Whereas if we write SQL, the syntax differs from database to database

The Query interface provides object-oriented methods and capabilities for representing and manipulating HQL queries.

Example of an HQL:

String queryStr = "SELECT e.name FROM Employee e";
Query query = session.createQuery(queryStr);
List results = query.list();

The attribute name is selected from the Entity Employee

Lazy Loading in Hibernate

Hibernate supports the following loading patterns

  • Eager Loading is a design pattern in which data initialization occurs on the spot.
  • Lazy Loading is a design pattern that we use to defer the initialization of an object as long as it’s possible and load only on demand

Lazy Loading is the default one and it makes the application efficient by not loading all the data and exhausting the DB Connection pool.

Eg: If a table has 1 million records and the relationship tables have another 1 million records. In case of lazy loading, it will only load the main table and only if requested, it will load data from the child tables.

Caching in Hibernate

Caching is the process of storing data into cache memory and improves the speed of data access.

Hibernate supports two levels of caching, first-level and second-level caching.

First Level Cache

The first level cache is a session-level cache and it is always associated with session-level object

Second Level Cache

Second-level cache is the session factory level cache and it is available across all sessions. For a second-level cache, we have to enable the cache and provide a cache provider like Ehcache and add its dependency.

Configuration

hibernate.cache.use_second_level_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
 

What is JPA?

JPA stands for Java Persistence API and it is the Java specification that defines how to persist java objects. It is considered as a link between an object-oriented model and a relational database system. Hibernate is the standard implementation of JPA. JPA cannot be used alone and it always needs an implementation like Hibernate, EclipseLink, iBatis, etc.

For data persistence, the java. persistence package contains the JPA classes and interfaces.

  1. JPA provides JPQL (Java Persistence Query Language) and HQL provided by Hibernate is a superset of it. Either can be used in the application.

2. JPA provides EntityManagerFactory interface whereas Hibernate provides SessionFactory to create the Session instances

3. For CRUD operations on instances of mapped entity classes, JPA uses EntityManager whereas Hibernate uses the Session interface

So, as seen above JPA provides its in-built stuff so that things won't break if we change to other ORM frameworks later and it will remain consistent.

But Hibernate provides advanced features and if you are sure that you will not change the ORM framework, then it's better to stick to the Hibernate specs.

 

What is Spring Data JPA?

There is always confusion between JPA and Spring Data JPA.

As we saw above, JPA is a standard for defining the persistence layer and Spring Data JPA is a sub-project under the Spring Framework umbrella which allows Spring applications to integrate with JPA.

Spring Data JPA is an abstraction that makes it easier to work with a JPA provider like Hibernate which is used by default. Specifically, Spring Data JPA provides a set of interfaces for easily creating data access repositories.

Before Spring Data JPA, we used to write all the CRUD methods in every single DAO and write an implementation for those. But then came Spring Data JPA, which abstracts the developer from that, and behind the scenes, it provides implementations for the basic crud methods. This avoids a lot of boilerplate code and makes it efficient for developers. We can still add custom methods and can use HQL or criteria etc.

Spring Data JPA also allows developers to use Transactional annotation to control the transaction boundaries.

Spring Data JPA comes with a concept called JPA Repository and Query methods. JPA Repository is nothing but a set of interfaces that defines query methods like findByFirstName or findByLastName etc. These methods are converted into low-level SQL queries by Spring.

Because of this cleaner approach, many Spring-based applications are using Spring Data JPA to implement their Data Access Layer or DAO Layer

The Spring Data Jpa dependency can be added as below and this will do the data source auto-configuration as well. After adding this, we just need to add a database dependency to make sure it is available in the class path.

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId><version>2.6.1</version></dependency>

Summary

in this article, we saw what is Hibernate, JPA, and Spring Data JPA. In a nutshell, JPA is a specification and we have to use one of its implementations to connect to the database. Spring Data JPA cannot work without a JPA provider and a JPA provider is mandatory to connect with the database. Spring Data JPA is not a mandatory one but it is for adding convenience to developers by removing the boilerplate code

Hope you all have enjoyed this article. Happy learning!!!

Please read my article on Transaction Management if you want to know more

 

'WEB > Spring JPA' 카테고리의 다른 글

Hibernate vs JPA vs Spring Data JPA  (0) 2022.06.07
JPA의 DTO와 Entity  (0) 2022.01.10
Spring Data JPA findBy Multiple Columns with Example  (0) 2022.01.09
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

❗️JPA의 DTO와 Entity

이번 시간에는 제가 JPA를 사용하면서 Entity와 DTO의 적절히 사용했던 경험에 대해 알려드리려고 합니다.

보통 회원가입 기능을 만든다고하면, 회원에 관련된 데이터베이스 컬럼과, 회원가입 폼에서 사용하는 컬럼은 대부분 다를 것 입니다.

회원가입의 Entity가 있다고 가정해 보겠습니다. 회원의 관련된 Entity인 User 클래스는 다음과 같습니다.

public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(nullable = false)
    private String email;

    private String nickname;

    @JsonIgnore
    private String password;

    @Column(columnDefinition="bit(1) default 1")
    private boolean enabled;

    @Column(columnDefinition="bit(1) default 1")
    private boolean acceptOptionalBenefitAlerts;

    private String fcmToken;

    private boolean privateAccount;
}

그러나 회원가입을 진행할 때 클라이언트로부터 받는 데이터는 email과 nickname 그리고 password만 필요합니다. 이 3개의 데이터를 어떻게 받아 올 수 있을까요?

저는 주로 각 기능마다 필요로 하는 필드들을 모은 DTO 클래스를 만들어 받습니다.

예를 들어 회원가입 로직이 들어가있는 API의 형태는 다음과 같습니다.

@PostMapping("/join")
public UserJoinResponse joinUser(@RequestBody @Valid UserJoinRequest userJoinRequest) {
	return userService.joinUser(userJoinRequest);
}

UserJoinRequest의 구성은 다음과 같습니다.

public class UserJoinRequest {
    @NotBlank(message = "이메일을 다시 확인해주세요.")
    String email;

    @NotBlank(message = "비밀번호를 다시 확인해주세요.")
    String password;

    @NotBlank(message = "닉네임을 다시 확인해주세요.")
    String nickname;
}

그러나 Service 단에서, DAO로 데이터를 저장시키기 위해서 이 DTO를 Entity로 변환해주는 작업이 필요합니다.

public UserJoinResponse joinUser(UserJoinRequest userJoinRequest) {
  User user=userRepository.save(user); //??
}

이 작업은 어떤 식으로 진행하는 것이 좋을까요?

UserJoinRequest를 User Entity로 변환해주는 책임은 바로 UserJoinRequest에게 있습니다. 그렇기 때문에 UserJoinRequest가 User로 변환을 해주는 로직이 필요합니다.

public class UserJoinRequest {
    @NotBlank(message = "이메일을 다시 확인해주세요.")
    String email;

    @NotBlank(message = "비밀번호를 다시 확인해주세요.")
    String password;

    @NotBlank(message = "닉네임을 다시 확인해주세요.")
    String nickname;

    public User toEntity() {
        return User.builder()
                .email(email)
                .nickname(nickname)
                .password(password)
                .build();
    }
}

toEntity() 함수에서 User 객체를 만들때는 Builder 패턴을 이용했습니다.

서비스 단에서는 다음과 같이 사용합니다.

public UserJoinResponse joinUser(UserJoinRequest userJoinRequest) {
  User saveUser = userJoinRequest.toEntity();
  User user = userRepository.save(user);
}

정상적으로 User가 데이터베이스에 저장되었다면, 클라이언트에게 보내줄 데이터를 만들어 보겠습니다.

저는 예제로 클라이언트에게 유저의 email을 클라이언트에게 보내보겠습니다. 현재 서비스단의 joinUser() 함수의 리턴 값은 UserJoinResponse 이기 때문에 User를 UserJoinResponse로 변경해주는 작업이 필요합니다.

이 또한 이 변경의 책임 은 누구한테 있는지 고민한다면 User 에게 있을 것입니다. 그러므로 User 클래스 안에 UserJoinResponse 객체를 만들어 주는 함수가 있어야 합니다.

회원가입이 성공적으로 완료되면 클라이언트에게 email 값을 주는 UserJoinResponse 입니다.

public class UserJoinResponse {
    String email;
}

User의 함수는 다음과 같습니다.

public class User {
	...필드 생략
	
	public UserJoinResponse toUserJoinResponse() {
		 return User.UserJoinResponse()
                .email(email)
                .build();
	}
}

지금까지 제가 JPA를 사용하면서 주로 사용했던 내용을 작성했습니다.

저는 위와 같은 방법을 주로 사용하지만, 이렇게 클래스마다 Entity <-> DTO 변환 클래스를 작성하지 않아도, 자동으로 변환해주는 라이브러리가 있어서 소개해 드리려고 합니다.

😯 ModelMapper

ModelMapper 라이브러리를 사용하게 되면 간편하게 Entity <-> DTO 변환이 가능해 집니다.

public UserJoinResponse joinUser(UserJoinRequest userJoinRequest) {
  ModelMapper mm = new ModelMapper(); 
  User user = new User();
  mm.map(userJoinRequest, user);
  User user =	userRepository.save(user);
}

이런 방법도 있지만, 개인적으로 처음 설명해드렸던 방법을 추천합니다.

🧐 Entity vs DTO

이렇게 특정 필드만 받을 수 있게 DTO 클래스를 만들었습니다. 그러나 프로젝트가 커지게 되면 DTO 클래스는 계속 증가합니다.

그냥 Entity 클래스를 받아서 필요한 값만 추출해서 사용하면 될것인데, 왜 굳이 이렇게 DTO 클래스를 새로 만들어서 사용 할까요?

DTO 클래스를 사용하는 이유는 다음과 같습니다.

서비스 단은 데이터베이스와 독립적이어야 합니다. 데이터베이스의 변경사항이 있으면, Entity를 사용하는 서비스 단에도 변경이 일어날 수 있습니다.

또한 Entity 클래스를 DTO로 재사용 하는 일은 코드가 더러워질 수 있습니다. 클래스가 DTO로써 사용 될 때 사용하는 메소드와 Entity로써 사용 될 때 사용하는 메소드가 공존하게 됩니다. 이런 점에서 관심사 가 깔끔하게 분리되지 않고, 클래스의 결합력만 높이게 됩니다.

참고문서

https://stackoverflow.com/questions/5216633/jpa-entities-and-vs-dtos

https://auth0.com/blog/automatically-mapping-dto-to-entity-on-spring-boot-apis/

'WEB > Spring JPA' 카테고리의 다른 글

Hibernate vs JPA vs Spring Data JPA  (0) 2022.06.07
JPA의 DTO와 Entity  (0) 2022.01.10
Spring Data JPA findBy Multiple Columns with Example  (0) 2022.01.09
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

Hey guys in this post, we discuss Data JPA finder methods by multiple field names with examples.

Overview


JPA finder methods are the most powerful methods, we can create finder methods to select the records from the database without writing SQL queries. Behind the scenes, Data JPA will create SQL queries based on the finder method and execute the query for us.

To create finder methods in Data JPA, we need to follow a certain naming convention. To create finder methods for the entity class field name, we need to create a method starting with findBy followed by field name. If we want to create finder methods for multiple field names then we need to use logical operators such as AND, OR between the field names. Consider the following Employee entity class which has 2 fields name and location

public class Employee {
	
	private String name;
	
	private String location;
	
	//setters and getters
}

To query the database that should match both name and location then we need to create a method like this –

findByNameAndLocation(String name, String location)

To query the database that should match any one of the columns then we need to create a method like this –

findByNameOrLocation(String name, String location)

Behind the scenes, Data JPA will create a SQL query like this –

SELECT * FROM employee WHERE name="employee name" AND location="location name";
SELECT * FROM employee WHERE name="employee name" OR location="location name";

As you can see, it’s so much easy to select the records with the help of finder methods. That’s the beauty of Data JPA.

NOTE: You can select any number of fields separated by logical operators.

Watch the video


 

Complete example


Let’s create a step-by-step spring boot project and create different finder methods for various fields.

Create database and insert sample data


Open MySQL workbench and execute the following commands

CREATE DATABASE mydb;

USE mydb;

CREATE TABLE tbl_laptops(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    description VARCHAR(255) NOT NULL,
    brand VARCHAR(255) NOT NULL,
    price DOUBLE(10, 2) NOT NULL
);

INSERT INTO tbl_laptops(name, description, brand, price)
VALUES("Dell Inspiron", "dell company laptop", "Dell", 60000.00);

INSERT INTO tbl_laptops(name, description, brand, price)
VALUES("Dell XPS", "dell company laptop", "Dell", 70000.00);

INSERT INTO tbl_laptops(name, description, brand, price)
VALUES("Macbook Air", "apple company laptop", "Apple", 85000.00);

INSERT INTO tbl_laptops(name, description, brand, price)
VALUES("Macbook Pro", "apple company laptop", "Apple", 160000.00);

INSERT INTO tbl_laptops(name, description, brand, price)
VALUES("HP", "hp company laptop", "HP", 50000.00);

INSERT INTO tbl_laptops(name, description, brand, price)
VALUES("Lenovo", "lenovo company laptop", "Lenovo", 50000.00);

SELECT * FROM tbl_laptops;

We have created a table tbl_laptops that contains 5 fields. We have inserted the sample data as well.

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>findbyfieldname</artifactId>
	<version>v1</version>
	<name>findbyfieldname</name>
	<description>Spring boot data jpa find by field name</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.




spring-boot-devtools dependency for automatic reloads or live reload of applications. spring-boot-starter-data-jpa dependency is a starter for using Spring Data JPA with Hibernate. lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString()

Create an entity class


Create Laptop.java inside the in.bushansirgur.springboot.entity package and add the following content

package in.bushansirgur.springboot.entity;

import java.math.BigDecimal;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Entity
@Data
@Table(name="tbl_laptops")
public class Laptop {
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	
	private String name;
	
	private String description;
	
	private String brand;
	
	private BigDecimal price;
}

We have added @Data annotation which is a Lombok annotation, that will automatically create setters, getters, toString(), and equals() for us.

@Entity is a mandatory annotation that indicates that this class is a JPA entity and is mapped with a database table.

@Table annotation is an optional annotation that contains the table info like table name.




@Id annotation is a mandatory annotation that marks a field as the primary key

Create a Repository


Create an interface LaptopRepository.java inside the in.bushansirgur.springboot.repos package and add the following content

package in.bushansirgur.springboot.repos;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import in.bushansirgur.springboot.entity.Laptop;

@Repository
public interface LaptopRepository extends JpaRepository<Laptop, Long> {
	
	List<Laptop> findByNameAndBrand(String name, String brand);
	
	List<Laptop> findByBrandAndPrice(String brand, BigDecimal Price);
	
	List<Laptop> findByNameOrBrandOrPrice(String name, String brand, BigDecimal price);
}

@Repository annotates classes at the persistence layer, which will act as a database repository. We have extended this interface with JPARepository interface which will provide built-in methods to interact with the database also we can define finder methods. We have defined 3 finder methods findByNameAndBrand(), findByBrandAndPrice() and findByNameOrBrandOrPrice() which will return the List<Laptops>

Create a Rest controller


Create LaptopController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springboot.controller;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import in.bushansirgur.springboot.entity.Laptop;
import in.bushansirgur.springboot.repos.LaptopRepository;

@RestController
public class LaptopController {
	
	@Autowired
	LaptopRepository lRepo;
	
	@GetMapping("/laptops/nameandbrand")
	public ResponseEntity<List<Laptop>> getLaptopsByNameAndBrand(@RequestParam String name, 
				@RequestParam String brand) {
		return new ResponseEntity<List<Laptop>>(lRepo.findByNameAndBrand(name, brand), HttpStatus.OK);
	}
	
	@GetMapping("/laptops/brandandprice")
	public ResponseEntity<List<Laptop>> getLaptopsByBrandAndPrice(@RequestParam String brand, 
				@RequestParam BigDecimal price) {
		return new ResponseEntity<List<Laptop>>(lRepo.findByBrandAndPrice(brand, price), HttpStatus.OK);
	}
	
	@GetMapping("/laptops/nameorbrandorprice")
	public ResponseEntity<List<Laptop>> getLaptopsByNameOrBrandOrPrice(@RequestParam String name, 
				@RequestParam String brand,	
				@RequestParam BigDecimal price) {
		return new ResponseEntity<List<Laptop>>(lRepo.findByNameOrBrandOrPrice(name, brand, price), HttpStatus.OK);
	}
}

We have auto wired the LaptopRepository using @Autowired annotation. We have created 3 handler methods, getLaptopsByNameAndBrand(), getLaptopsByBrandAndPrice() and getLaptopsByNameOrBrandOrPrice() which will call the repository methods findByNameAndBrand(), findByBrandAndPrice() and findByNameOrBrandOrPrice() respectively.

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL –

  • http://localhost:8080/laptops/nameandbrand?name=dell inspiron&brand=dell
[
    {
        "id": 1,
        "name": "Dell Inspiron",
        "brand": "Dell",
        "description": "dell company laptop",
        "price": 60000.0
    }
]
  • http://localhost:8080/laptops/brandandprice?brand=hp&price=50000.00
[
    {
        "id": 5,
        "name": "HP",
        "brand": "HP",
        "description": "hp company laptop",
        "price": 50000.0
    }
]
  • http://localhost:8080/laptops/nameorbrandorprice?name=acer&brand=apple&price=90000.00
[
    {
        "id": 3,
        "name": "Macbook Air",
        "brand": "Apple",
        "description": "apple company laptop",
        "price": 85000.0
    },
    {
        "id": 4,
        "name": "Macbook Pro",
        "brand": "Apple",
        "description": "apple company laptop",
        "price": 160000.0
    }
]

References


'WEB > Spring JPA' 카테고리의 다른 글

Hibernate vs JPA vs Spring Data JPA  (0) 2022.06.07
JPA의 DTO와 Entity  (0) 2022.01.10
Spring Data JPA findBy Multiple Columns with Example  (0) 2022.01.09
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

47
18

What does static mean?

I know public means that it can be accessed from outside the class, and private only from inside the class…

 

 

42
 

Static means that it can be accessed without instantiating a class. This is good for constants.

Static methods need to have no effect on the state of the object. They can have local variables in addition to the parameters.'

 

 

 

 

40

public: Public declared items can be accessed everywhere.

protected: Protected limits access to inherited and parent classes (and to the class that defines the item).

private: Private limits visibility only to the class that defines the item.

static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

final: Final keywords prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.


Beside of PHP:

transient: A transient variable is a variable that may not be serialized.

volatile: A variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile won't be optimized by the compiler because their value can change at anytime.

 

 

 

0

Example:

public class Methods_Test1 
{   
    public static void Display(String Name)
    {
        System.out.println("Hello There " + Name);
        System.out.println("I am from Display method");
    }


    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter name");
        String name = sc.next();
        Obj.Display(name);

    }

The public static void Display(String name) method accessible as static method within its own class which can be accessed without creating object of the class where as the same method behaves as public for the outside classes which can be accessed by creating object.

 

 

 

'WEB > PHP' 카테고리의 다른 글

The difference between "public" and "public static"?  (0) 2021.11.23
PHP 실행 지연(delay) 시키기  (0) 2021.11.23
mb_substr  (0) 2021.09.13
PHP Superglobal - $_REQUEST  (0) 2021.08.18
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

PHP 스크립트(script) 실행(execution)시 테스트 등의 목적으로 실행을 지연(delay)시켜야할 경우가 있습니다. 이때 사용할 수 있는 함수 입니다.

 

 

1. 초 단위로 지연

 

int sleep ( int $seconds )

 

$seconds로 주어진 초 만큼 실행을 지연합니다. 성공시 0을 반환, 실패시 FALSE를 반환합니다. 음수를 지정하면 오류입니다. Warning이 발생합니다.

 

<?php
// ...
// 2초간 지연합니다.
sleep(2);
//...
?>

 

 

2. 마이크로초 단위로 지연

 

void usleep ( int $micro_seconds )

 

$micro_seconds로 주어인 마이크로 초(백만분의 1초) 만큼 실행을 지연합니다. 값을 반환하지 않습니다. 음수를 지정하면 오류입니다. Warning이 발생합니다.

 

<?php
// ...
// 2초간 지연합니다.
usleep(2000000);
// ...
?>

 

 

3. 지정된 시간까지 지연

 

bool time_sleep_until ( float $timestamp )

 

$timestamp 로 주어진 시간까지 지연합니다. 성공시 TRUE, 실패시 FALSE를 반환합니다. 과거 시간을 지정하면 오류입니다. Warning이 발생합니다.

 

<?php // 2초 지연 time_sleep_until(time() + 2); // 0.2초 지연 time_sleep_until(microtime(true) + 0.2); ?>

 

※ 참고

- int time(void) : January 1 1970 00:00:00 GMT 부터 지금까지의 초를 반환합니다.

- mixed microtime ([ bool $get_as_float = false ] ) : 현재의 타임스탬프를 마이크로초로 반환합니다. 인자로 주어지는 $get_as_float가 TRUE이면 마이크로초에 가장 근접한 초값을 float 타입으로 반환하고, FALSE 이면 string 타입의 값을 반환합니다.

 

PHP 프로그램을 지연시키는 다양한 방법을 알아보았습니다.



출처: https://offbyone.tistory.com/197 [쉬고 싶은 개발자]

'WEB > PHP' 카테고리의 다른 글

The difference between "public" and "public static"?  (0) 2021.11.23
PHP 실행 지연(delay) 시키기  (0) 2021.11.23
mb_substr  (0) 2021.09.13
PHP Superglobal - $_REQUEST  (0) 2021.08.18
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

Class 'ZipArchive' not found 에러가 발생하는 이유는 zip 모듈이 없어서이다.

phpinfo() 하여서 확인해보면 알 수 있다.

 

모듈을 설치하려면 PHP 다시 컴파일하거나 모듈만 설치하는 방법이 있다.

귀찮으니 모듈만 따로 설치하자.

Zip 모듈은 pecl 에서 다운로드 받으면 된다. 여기서 Stable 버전을 다운받는다.

http://pecl.php.net/package/zip

 

wget http://pecl.php.net/get/zip-1.10.2.tgz

압축을 해제하고

tar xvfz zip-1.10.2.tgz

cd zip-1.10.2

phpize     (혹시 phpize: command not found 라고 나오면 yum install php-devel  한후 다시 실행)

./configure --with-php-config=/usr/local/php/bin/php-config --enable-zip && make

cd modules/

ls 를 하면 zip.la  zip.so 가 보인다.

zip.so를 php 확장 디렉토리로 복사한다.

cp zip.so /usr/local/php/lib/php/extensions

php 설정파일을 열어서 zip.so 부분을 추가해준다.

vi /etc/php.ini

extension_dir="/usr/local/php/lib/php/extensions"

extension="zip.so" 를 추가.

/usr/local/apache2/bin/apachectl restart



출처: https://mara.tistory.com/327 [Absolute Purpose]

 

In CentOS 7.4 

yum install php-pecl-zip

 

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

mb_substr

WEB/PHP 2021. 9. 13. 21:26

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_substr  Get part of string

Description 

mb_substr(
    string $string,
    int $start,
    ?int $length = null,
    ?string $encoding = null
): string

Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of string. First character's position is 0. Second character position is 1, and so on.

Parameters 

string

The string to extract the substring from.

start

If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If start is negative, the returned string will start at the start'th character from the end of string.

length

Maximum number of characters to use from string. If omitted or NULL is passed, extract all characters to the end of the string.

encoding

The encoding parameter is the character encoding. If it is omitted or null, the internal character encoding value will be used.

Return Values 

mb_substr() returns the portion of string specified by the start and length parameters.

Changelog 

VersionDescription

8.0.0 encoding is nullable now.

See Also 

https://www.php.net/manual/en/function.mb-substr

 

'WEB > PHP' 카테고리의 다른 글

The difference between "public" and "public static"?  (0) 2021.11.23
PHP 실행 지연(delay) 시키기  (0) 2021.11.23
mb_substr  (0) 2021.09.13
PHP Superglobal - $_REQUEST  (0) 2021.08.18
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

Super global variables are built-in variables that are always available in all scopes.


PHP $_REQUEST

PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field:

Example

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // collect value of input field
  $name = $_REQUEST['fname'];
  if (empty($name)) {
    echo "Name is empty";
  } else {
    echo $name;
  }
}
?>


</body>
</html>

'WEB > PHP' 카테고리의 다른 글

The difference between "public" and "public static"?  (0) 2021.11.23
PHP 실행 지연(delay) 시키기  (0) 2021.11.23
mb_substr  (0) 2021.09.13
PHP Superglobal - $_REQUEST  (0) 2021.08.18
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요