2024. 3. 11. 18:20ㆍDaily Codig Reminder
h2
h2
DROP TABLE IF EXISTS USER;
CREATE TABLE IF NOT EXISTS USER(
ID NUMBER IDENTITY PRIMARY KEY, -- identity는 auto increment 값이다.
NAME VARCHAR(50),
ADDRESS VARCHAR(50)
);
INSERT INTO USER(NAME, ADDRESS) VALUES('HONG', 'SEOUL');
INSERT INTO USER(NAME, ADDRESS) VALUES('KIM', 'BUSAN');
INSERT INTO USER(NAME, ADDRESS) VALUES('LEE', 'INCHEON');
drop table user;
application.properties
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.dbcp2.password=
@SpringBootApplication
public class Boot12Db1SpringDataJdbc1H2EmbeddedApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Boot12Db1SpringDataJdbc1H2EmbeddedApplication.class, args);
UserService service= ctx.getBean("myService",UserService.class);
// ((UserRepositoryImpl)service).test();
int num = service.insert(new User("홍길동","서울"));
System.out.println("insert 갯수: "+num);
}
}
@Repository
public interface UserRepository {
public abstract List<User> selectAll(JdbcTemplate session);
public abstract User selectById(JdbcTemplate session, int id);
public abstract int insert(JdbcTemplate session, User user);
public abstract int update(JdbcTemplate session, User user);
public abstract int delete(JdbcTemplate session, int id);
}
@Repository
public class UserRepositoryImpl implements UserRepository {
@Override
public List<User> selectAll(JdbcTemplate session) {
String sql = "select id, name, address from user";
return session.query(sql, new RowMapper<User>() {
@Override
public User mapRow (ResultSet rs, int rowNum)throws SQLException{
return new User (rs.getInt("id"), rs.getString("name"), rs.getString("address"));
}
});//end
}//end
@Override
public User selectById(JdbcTemplate session, int id) {
String sql="select id, name, address from user where id=?";
return session.queryForObject(sql, new RowMapper<User>() {
@Override
public User mapRow (ResultSet rs, int rowNum)throws SQLException{
return new User (rs.getInt("id"), rs.getString("name"), rs.getString("address"));
}
},id);//end
}
@Override
public int insert(JdbcTemplate session, User user) {
String sql ="insert into user (name, address) values (?,?)";
return session.update(sql, user.getName(), user.getAddress());
}
@Override
public int update(JdbcTemplate session, User user) {
String sql ="update into user (name, address) values (?,?)";
return session.update(sql, user.getName(), user.getAddress());
}
public class User {
private int id;
private String name;
private String address;
public interface UserService {
public abstract List<User> selectAll();
public abstract User selectById(int id);
public abstract int insert(User user);
public abstract int update(User user);
public abstract int delete(int id);
}
@Service("myService")
public class UserServieImpl implements UserService {
@Autowired
UserRepository repository;
@Autowired
JdbcTemplate session;
@Override
public List<User> selectAll() {
return repository.selectAll(session);
}
@Override
public User selectById(int id) {
return repository.selectById(session,id);
}
@Override
public int insert(User user) {
return repository.insert(session, user);
}
@Override
public int update(User user) {
return repository.update(session, user);
}
@Override
public int delete(int id) {
return repository.delete(session, id);
}
}
#jdbcTemplate 자동생성
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.dbcp2.password=
jpa-h2
user table crud table 생성 dao 구현 dto 구현 service 구현 메인 test
jpa 기술
- dto 기준 ⇒ table 생성자동
- dao crud ⇒ crud 코드 자동 생성 , sql 작성 필요 없음.
dao interface 만 작성 ⇒ 실제 코드 구현은 boot 에서
#jdbcTemplate 자동생성
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.dbcp2.password=
#Spring.jpa.hiberate.ddl-auto=create dto 를 기준으로 테이블 생성 여부
#최초 실행시 crete 이후 none 으로 변경
spring.jpa.hibernate.ddl-auto=create
#sql 정보 출력
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
package com.example.service;
import java.util.List;
import java.util.Optional;
import com.example.dto.User;
public interface UserService {
public abstract List<User> findAll();
public abstract Optional<User> findById(int id);
public abstract User save(User user);
public abstract User update (User user);
public abstract void delete (int id);
}
package com.example.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.JpaUserRepository;
import com.example.dto.User;
@Service("myService")
public class UserServieImpl implements UserService{
@Autowired
JpaUserRepository repository;
@Override
public List<User> findAll() {
return repository.findAll();
}
@Override
public Optional<User> findById(int id) {
// TODO Auto-generated method stub
return repository.findById(id);
}
@Override
public User save(User user) {
// TODO Auto-generated method stub
return repository.save(user);
}
@Override
public User update(User user) {
// TODO Auto-generated method stub
return repository.save(user);
}
@Override
public void delete(int id) {
repository.deleteById(id);
}
}
package com.example.dto;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity////table 생성 모델
public class User {
//Id컬럼지정, DB서버의 키 값을 설정
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//자동 추가 설정
private int id;
private String name;
private String address;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", address=" + address + "]";
}
public User(String name, String address) {
super();
this.name = name;
this.address = address;
}
}
package com.example.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.dto.User;
@Repository
public interface JpaUserRepository extends JpaRepository<User, Integer> {
//JpaUserRepository 를 이용하여 Spring 에서 구현해줌
//구현을 위한 콛는 개발자가 아닌 Spring에서 처리함
//User 클랫스를 Entity 로 지정하고 id/key 의 데이터 타입을 Integet 로 정함
//실제 dao impl 구현 필요 없음 => 자동생성
//전체 select findall()
//insert save()
//update save()
//delete deleteById()
//selectID findByID()
}
package com.example;
import java.util.List;
import java.util.Optional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.example.dto.User;
import com.example.service.UserService;
@SpringBootApplication
public class Boot12Db2SpringDataJpaH2ServerApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Boot12Db2SpringDataJpaH2ServerApplication.class, args);
UserService service= ctx.getBean("myService",UserService.class);
//insert 후 실행함
//1. 데이터 insert
User user = service.save(new User("홍길동","서울"));
System.out.println("insert data: "+user);
//1.모든 데이터
List<User> xx = service.findAll();
for (User u : xx) {
System.out.println(u);
//2.update 전
User user2 = new User(1, "홍길동","서울");
user2.setAddress("aaa");
System.out.println("update 전 db: "+user2);
//2.update 후
User upuser = service.update(user2);
System.out.println(upuser);
//3. 특정데이터
Optional<User> op = service.findById(1);
System.out.println("find by id: "+op.get());
System.out.println("===============");
//1.모든 데이터
List<User> xx2 = service.findAll();
for (User u2 : xx2) {
System.out.println(u2);
}
}}
}
User [id=1, name=홍길동, address=aaa]
Hibernate: select user0_.id as id1_0_0_, user0_.address as address2_0_0_, user0_.name as name3_0_0_ from user user0_ where user0_.id=? find by id: User [id=1, name=홍길동, address=aaa]
Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.name as name3_0_ from user user0_
User [id=1, name=홍길동, address=aaa]
jpa-oracle
#데이터 소스 설정
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=scott
spring.datasource.password=tiger
#최초 create, 이후 none으로 변경
spring.jpa.hibernate.ddl-auto=create
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.database=oracle
logging.level.org.hibernate=info
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
dto
package com.example.dto;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="UserTest") //생성된 테이블 이름 지정 가능
public class UserTest {
//Id컬럼지정, DB서버의 키 값을 설정
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String address;
public UserTest() {
super();
// TODO Auto-generated constructor stub
}
public UserTest(int id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
public UserTest(String name, String address) {
super();
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}
package com.example.service;
import java.util.List;
import java.util.Optional;
import com.example.dto.UserTest;
public interface UserService {
public abstract List<UserTest> findAll();
public abstract Optional<UserTest> findById(int id);
public abstract UserTest save(UserTest user);
public abstract UserTest update(UserTest user);
public abstract void delete(int id);
}
package com.example.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.JpaUserRepository;
import com.example.dto.UserTest;
@Service("myService")
public class UserServieImpl implements UserService{
@Autowired
JpaUserRepository repository;
@Override
public List<UserTest> findAll() {
// TODO Auto-generated method stub
return repository.findAll();
}
@Override
public Optional<UserTest> findById(int id) {
// TODO Auto-generated method stub
return repository.findById(id);
}
@Override
public UserTest save(UserTest user) {
// TODO Auto-generated method stub
return repository.save(user);
}
@Override
public UserTest update(UserTest user) {
// TODO Auto-generated method stub
return repository.save(user);
}
@Override
public void delete(int id) {
// TODO Auto-generated method stub
repository.deleteById(id);
}
}
package com.example.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.dto.UserTest;
public interface JpaUserRepository extends JpaRepository<UserTest, Integer>{
//JpaUserRepository를 이용하여 Spring에서 구현 해줌
//구현을 위한 코드는 개발자가 아닌 Spring에서 처리함
//User 클래스를 Entity로 지정하고 , Id/Key의 데이터 타입을 Integer로 정함
}
package com.example;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.context.ApplicationContext;
import com.example.dto.UserTest;
import com.example.service.UserService;
@SpringBootApplication
public class Sample06BeanApplication {
public static void main(String[] args) {
ApplicationContext ctx=SpringApplication.run(Sample06BeanApplication.class, args);
UserService serivce= ctx.getBean("myService", UserService.class);
//insert 후 실행함
//1. 데이터 insert
UserTest user= serivce.save(new UserTest("변의주","서울"));
System.out.println("insert 데이터 : "+ user);
//1.모든 데이터
List<UserTest> xx= serivce.findAll();
for (UserTest u : xx) {
System.out.println(">>>>>"+u);
}
}
}
mybatis
main
@SpringBootApplication
public class Boot12Db3Mybatis2Oracle11gApplication {
public static void main(String[] args) {
ApplicationContext ctx=SpringApplication.run(Boot12Db3Mybatis2Oracle11gApplication.class, args);
DBService service= ctx.getBean("myService", DBService.class);
//serivce.test();
//((DBOracleService)serivce).test();
List<Dept> list = service.list();
System.out.println(list);
//1. 저장
// int num= service.insert(new Dept(77, "개발","서울"));
//2. 수정
// int num2 = service.update(new Dept(77,"aa","aa"));
// //3.삭제
int num3 = service.delete(77);
for (Dept dept : list) {
System.out.println(dept);
}
}
}
DBService
public interface DBService {
public abstract List<Dept> list();
public abstract int insert(Dept dept);
public abstract int update(Dept dept);
public abstract int delete(int deptno);
}
@Repository
public class DBOracleDAO implements DBDao {
@Override
public List<Dept> list(SqlSessionTemplate session) {
// TODO Auto-generated method stub
return session.selectList("selectAll");
}
@Override
public int insert(SqlSessionTemplate session, Dept dept) {
// TODO Auto-generated method stub
return session.insert("insert", dept);
}
@Override
public int update(SqlSessionTemplate session, Dept dept) {
// TODO Auto-generated method stub
return session.update("update",dept);
}
@Override
public int delete(SqlSessionTemplate session, int deptno) {
// TODO Auto-generated method stub
return session.delete("delete",deptno);
}
}
public interface DBDao {
List<Dept> list(SqlSessionTemplate session);
int insert(SqlSessionTemplate session, Dept dept);
int update(SqlSessionTemplate session, Dept dept);
int delete(SqlSessionTemplate session, int deptno);
}
@Alias("Dept")
public class Dept {
mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dto">
<!-- sql 삭제해서 맵퍼 작성할 것 -->
<select id="selectAll" resultType="com.example.dto.Dept"><!-- 결과를 Dept의 List형태로 -->
select deptno,dname, loc from dept
</select>
<insert id="insert" parameterType="Dept">
insert into dept (deptno, dname, loc)
values (#{deptno}, #{dname},#{loc})
</insert>
<update id="update" parameterType="Dept">
update dept
set dname = #{dname} , loc = #{loc}
where deptno = #{deptno}
</update>
<delete id="delete" parameterType="int">
delete from dept
where deptno = #{deptno}
</delete>
</mapper>
mybatis2
@Mapper
public interface DBDao {
//1. sqlsessiontemplate는 @mapper 사용시 사용됨
//2. 매퍼의 namespace 를 dbdao 와 일치시킴
//<mapper namespace="com.example.dao.DBDao">
//3. 매퍼 id와 함수 이름 통일, 리턴 타입, 매개변수 통일
//4. dao 구현 별도 필요없음
public abstract List<Dept> selectAll();
public abstract int insert(Dept dto);
public abstract int update(Dept dto);
public abstract int delete(int deptno);
mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.DBDao">
<!-- sql 삭제해서 맵퍼 작성할 것 -->
<select id="selectAll" resultType="com.example.dto.Dept"><!-- 결과를 Dept의 List형태로 -->
select deptno,dname, loc from dept
</select>
<insert id="insert" parameterType="DeptDTO">
insert into dept (deptno, dname, loc)
values (#{deptno}, #{dname},#{loc})
</insert>
<update id="update" parameterType="DeptDTO">
update dept
set dname = #{dname} , loc = #{loc}
where deptno = #{deptno}
</update>
<delete id="delete" parameterType="int">
delete from dept
where deptno = #{deptno}
</delete>
</mapper>
package com.example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.DBDao;
import com.example.dto.Dept;
@Service("myService")
public class DBOracleService implements DBService {
@Autowired
DBDao dao;
@Override
public List<Dept> list() {
// TODO Auto-generated method stub
return dao.selectAll();
}
@Override
public int insert(Dept dto) {
// TODO Auto-generated method stub
return dao.insert(dto);
}
@Override
public int update(Dept dto) {
// TODO Auto-generated method stub
return dao.update(dto);
}
@Override
public int delete(int deptno) {
// TODO Auto-generated method stub
return dao.delete(deptno);
}
}
public interface DBService {
public abstract List<Dept> list();
public abstract int insert(Dept dto);
public abstract int update(Dept dto);
public abstract int delete(int deptno);
}
transaction
package com.example;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.example.dto.Dept;
import com.example.service.DBService;
@SpringBootApplication
public class Boot12Db3Mybatis2Oracle11gApplication {
public static void main(String[] args) {
ApplicationContext ctx=SpringApplication.run(Boot12Db3Mybatis2Oracle11gApplication.class, args);
DBService service= ctx.getBean("myService", DBService.class);
//serivce.test();
//((DBOracleService)serivce).test();
// List<Dept> list = service.list();
// System.out.println(list);
//1. 저장
// int num= service.insert(new Dept(77, "개발","서울"));
//2. 수정
// int num2 = service.update(new Dept(77,"aa","aa"));
// //3.삭제
// int num3 = service.delete(77);
// for (Dept dept : list) {
// System.out.println(dept);
// }
try {
service.txTest(new Dept(22, "개발","서울"),80);
//insert ok, del 시 exception발생
} catch (Exception e) {
e.printStackTrace();
System.out.println("에러 발생");
}
List<Dept> list = service.list();
for (Dept dept : list) {
System.out.println(dept);
}
System.out.println(list);
}
}
public interface DBDao {
List<Dept> list(SqlSessionTemplate session);
int insert(SqlSessionTemplate session, Dept dept);
int update(SqlSessionTemplate session, Dept dept);
int delete(SqlSessionTemplate session, int deptno);
int delete2(SqlSessionTemplate session, int deptno);
}
@Repository
public class DBOracleDAO implements DBDao {
@Override
public List<Dept> list(SqlSessionTemplate session) {
// TODO Auto-generated method stub
return session.selectList("selectAll");
}
@Override
public int insert(SqlSessionTemplate session, Dept dept) {
// TODO Auto-generated method stub
return session.insert("insert", dept);
}
@Override
public int update(SqlSessionTemplate session, Dept dept) {
// TODO Auto-generated method stub
return session.update("update",dept);
}
@Override
public int delete(SqlSessionTemplate session, int deptno) {
// TODO Auto-generated method stub
return session.delete("delete",deptno);
}
@Override
public int delete2(SqlSessionTemplate session, int deptno) {
// TODO Auto-generated method stub
return session.delete("delete2",deptno);
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dto">
<!-- sql 삭제해서 맵퍼 작성할 것 -->
<select id="selectAll" resultType="com.example.dto.Dept"><!-- 결과를 Dept의 List형태로 -->
select deptno,dname, loc from dept
</select>
<insert id="insert" parameterType="Dept">
insert into dept (deptno, dname, loc)
values (#{deptno}, #{dname},#{loc})
</insert>
<update id="update" parameterType="Dept">
update dept
set dname = #{dname} , loc = #{loc}
where deptno = #{deptno}
</update>
<delete id="delete" parameterType="int">
delete from dept
where deptno = #{deptno}
</delete>
<delete id="delete2" parameterType="int">
delete from dept
where deptno =
</delete>
</mapper>
package com.example.service;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.dao.DBDao;
import com.example.dto.Dept;
@Service("myService")
public class DBOracleService implements DBService {
@Autowired
DBDao dao;
@Autowired
SqlSessionTemplate session;
@Override
public List<Dept> list() {
// TODO Auto-generated method stub
return dao.list(session);
}
@Override
public int insert(Dept dept) {
// TODO Auto-generated method stub
return dao.insert(session, dept);
}
@Override
public int update(Dept dept) {
// TODO Auto-generated method stub
return dao.update(session, dept);
}
@Override
public int delete(int deptno) {
// TODO Auto-generated method stub
return dao.delete(session, deptno);
}
@Transactional
@Override
public void txTest(Dept dept, int i) throws Exception{
int num = dao.insert(session, dept);
System.out.println("insert num="+dept);
dao.delete2(session, i);
}
}
package com.example.service;
import java.util.List;
import com.example.dto.Dept;
public interface DBService {
public abstract List<Dept> list();
public abstract int insert(Dept dept);
public abstract int update(Dept dept);
public abstract int delete(int deptno);
public abstract void txTest(Dept dept, int i) throws Exception;
}
#데이터 소스 설정
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=scott
spring.datasource.password=tiger
#mybatis 설정
mybatis.mapper-locations=com/example/mapper/*.xml
mybatis.type-aliases-package=com.example.*
insert num=Dept [deptno=22, dname=개발, loc=서울]
에러 발생
Dept [deptno=10, dname=ACCOUNTING, loc=NEW YORK]
Dept [deptno=20, dname=RESEARCH, loc=DALLAS]
Dept [deptno=30, dname=SALES, loc=CHICAGO]
Dept [deptno=40, dname=OPERATIONS, loc=BOSTON]
Dept [deptno=50, dname=aa, loc=제주]
Dept [deptno=99, dname=aa, loc=서울]
Dept [deptno=92, dname=bb, loc=bb]
Dept [deptno=88, dname=영업, loc=제주]
Dept [deptno=12, dname=aa, loc=aa]
Dept [deptno=13, dname=bb, loc=bb]
Dept [deptno=91, dname=aa, loc=aa]
Dept [deptno=44, dname=개발, loc=서울]
Dept [deptno=66, dname=개발, loc=서울]
Dept [deptno=55, dname=개발, loc=서울]
Dept [deptno=33, dname=개발, loc=서울]
mybatis-jsp
@Controller
public class MainController {
@RequestMapping(value = "/")
public String main() {
System.out.println("/주소요청");
System.out.println("/주소요청33333");
return "main";
}
}
#내장 tomcat
server.port=8090
server.servlet.context-path=/app
#view-resolver
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
'Daily Codig Reminder' 카테고리의 다른 글
redirect,thymeleaf (0) | 2024.03.12 |
---|---|
boot-mybatis (0) | 2024.03.12 |
component-scan (0) | 2024.03.11 |
list, map, @Autowired (1) | 2024.02.28 |
springboot (1) | 2024.02.28 |