Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 332bf40

Browse files
Spring Datos con Hibernate JPA
Integración del ORM Hibernate con Spring usando la API JPA.
1 parent 6b95ca4 commit 332bf40

File tree

11 files changed

+480
-0
lines changed

11 files changed

+480
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project-shared-configuration>
3+
<!--
4+
This file contains additional configuration written by modules in the NetBeans IDE.
5+
The configuration is intended to be shared among all the users of project and
6+
therefore it is assumed to be part of version control checkout.
7+
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
8+
-->
9+
<spring-data xmlns="http://www.netbeans.org/ns/spring-data/1">
10+
<config-files>
11+
<config-file>src/main/resources/springXMLConfig.xml</config-file>
12+
<config-file>src/main/resources/beans.xml</config-file>
13+
</config-files>
14+
<config-file-groups/>
15+
</spring-data>
16+
</project-shared-configuration>

‎tutorial_hibernate_jpa/nbactions.xml

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<actions>
3+
<action>
4+
<actionName>run</actionName>
5+
<packagings>
6+
<packaging>jar</packaging>
7+
</packagings>
8+
<goals>
9+
<goal>process-classes</goal>
10+
<goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
11+
</goals>
12+
<properties>
13+
<exec.args>-classpath %classpath carmelo.spring.jpa.SpringHibernateJpa</exec.args>
14+
<exec.executable>java</exec.executable>
15+
</properties>
16+
</action>
17+
<action>
18+
<actionName>debug</actionName>
19+
<packagings>
20+
<packaging>jar</packaging>
21+
</packagings>
22+
<goals>
23+
<goal>process-classes</goal>
24+
<goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
25+
</goals>
26+
<properties>
27+
<exec.args>-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -classpath %classpath carmelo.spring.jpa.SpringHibernateJpa</exec.args>
28+
<exec.executable>java</exec.executable>
29+
<jpda.listen>true</jpda.listen>
30+
</properties>
31+
</action>
32+
<action>
33+
<actionName>profile</actionName>
34+
<packagings>
35+
<packaging>jar</packaging>
36+
</packagings>
37+
<goals>
38+
<goal>process-classes</goal>
39+
<goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
40+
</goals>
41+
<properties>
42+
<exec.args>-classpath %classpath carmelo.spring.jpa.SpringHibernateJpa</exec.args>
43+
<exec.executable>java</exec.executable>
44+
</properties>
45+
</action>
46+
</actions>

‎tutorial_hibernate_jpa/pom.xml

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>carmelo.spring</groupId>
5+
<artifactId>tutorial_hibernate_jpa</artifactId>
6+
<version>1.0</version>
7+
<packaging>jar</packaging>
8+
9+
<dependencies>
10+
<dependency>
11+
<groupId>org.springframework</groupId>
12+
<artifactId>spring-context</artifactId>
13+
<version>4.3.6.RELEASE</version>
14+
</dependency>
15+
<dependency>
16+
<groupId>org.springframework</groupId>
17+
<artifactId>spring-orm</artifactId>
18+
<version>4.3.6.RELEASE</version>
19+
</dependency>
20+
21+
<dependency>
22+
<groupId>org.hibernate</groupId>
23+
<artifactId>hibernate-core</artifactId>
24+
<version>4.3.11.Final</version>
25+
</dependency>
26+
<dependency>
27+
<groupId>org.hibernate</groupId>
28+
<artifactId>hibernate-entitymanager</artifactId>
29+
<version>4.3.11.Final</version>
30+
</dependency>
31+
32+
<dependency>
33+
<groupId>org.hsqldb</groupId>
34+
<artifactId>hsqldb</artifactId>
35+
<version>2.3.3</version>
36+
<scope>runtime</scope>
37+
</dependency>
38+
</dependencies>
39+
40+
<properties>
41+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
42+
<maven.compiler.source>1.8</maven.compiler.source>
43+
<maven.compiler.target>1.8</maven.compiler.target>
44+
</properties>
45+
46+
</project>
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package carmelo.spring.jpa;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import javax.persistence.EntityManagerFactory;
6+
import javax.sql.DataSource;
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.context.annotation.Bean;
9+
import org.springframework.context.annotation.ComponentScan;
10+
import org.springframework.context.annotation.Configuration;
11+
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
12+
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
13+
import org.springframework.orm.jpa.JpaTransactionManager;
14+
import org.springframework.orm.jpa.JpaVendorAdapter;
15+
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
16+
import org.springframework.orm.jpa.vendor.Database;
17+
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
18+
import org.springframework.transaction.PlatformTransactionManager;
19+
import org.springframework.transaction.annotation.EnableTransactionManagement;
20+
21+
@Configuration
22+
@ComponentScan(basePackages = "carmelo.spring.jpa.dao")
23+
@EnableTransactionManagement
24+
public class SpringConfiguration {
25+
26+
@Bean
27+
public DataSource dataSource() {
28+
return new EmbeddedDatabaseBuilder()
29+
.setType(EmbeddedDatabaseType.HSQL)
30+
.addScript("classpath:schema.sql")
31+
.addScript("classpath:data.sql")
32+
.generateUniqueName(true)
33+
.build();
34+
}
35+
36+
@Bean
37+
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
38+
LocalContainerEntityManagerFactoryBean factoryBean
39+
= new LocalContainerEntityManagerFactoryBean();
40+
factoryBean.setDataSource(dataSource());
41+
factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
42+
factoryBean.setPackagesToScan("carmelo.spring.jpa.model");
43+
factoryBean.setPersistenceUnitName("pun-hibernate-jpa");
44+
45+
Map<String, String> props = new HashMap<>();
46+
props.put("hibernate.format_sql", "true");
47+
48+
factoryBean.setJpaPropertyMap(props);
49+
50+
return factoryBean;
51+
}
52+
53+
@Bean
54+
public JpaVendorAdapter jpaVendorAdapter() {
55+
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
56+
jpaVendorAdapter.setGenerateDdl(false);
57+
jpaVendorAdapter.setDatabase(Database.HSQL);
58+
jpaVendorAdapter.setShowSql(false);
59+
return jpaVendorAdapter;
60+
}
61+
62+
@Bean
63+
@Autowired
64+
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
65+
JpaTransactionManager transactionManager = new JpaTransactionManager();
66+
transactionManager.setEntityManagerFactory(entityManagerFactory);
67+
return transactionManager;
68+
}
69+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package carmelo.spring.jpa;
2+
3+
import java.sql.SQLException;
4+
import carmelo.spring.jpa.dao.ProductDao;
5+
import carmelo.spring.jpa.model.Product;
6+
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
7+
import org.springframework.context.support.AbstractApplicationContext;
8+
9+
public class SpringHibernateJpa {
10+
11+
public static void main(String[] args) throws SQLException {
12+
13+
AbstractApplicationContext ctx
14+
= new AnnotationConfigApplicationContext(SpringConfiguration.class);
15+
16+
// obtener bean DAO
17+
ProductDao product = ctx.getBean("productDaoJpa", ProductDao.class);
18+
19+
// contar los productos
20+
System.out.println("Cantidad de productos: " + product.cantidad());
21+
22+
// buscar el producto con ID = 5
23+
Product p_5 = product.buscar(5);
24+
System.out.println("ID = 5: " + p_5);
25+
26+
// insertar nuevo producto
27+
product.insertar(new Product(11, "Computer", 800.25));
28+
29+
// eliminar el producto con ID = 5
30+
product.eliminar(p_5.getId());
31+
32+
// actualizar precio de un producto
33+
Product p_3 = product.buscar(3);
34+
p_3.setPrice(1111.0);
35+
product.actualizar(p_3);
36+
37+
// listar todos los productos
38+
product.todos().forEach(System.out::println);
39+
40+
41+
ctx.close();
42+
}
43+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package carmelo.spring.jpa.dao;
2+
3+
import carmelo.spring.jpa.model.Product;
4+
import java.util.List;
5+
6+
public interface ProductDao {
7+
8+
List<Product> todos();
9+
10+
Integer cantidad();
11+
12+
Product buscar(Integer id);
13+
14+
void insertar(Product product);
15+
16+
void actualizar(Product product);
17+
18+
void eliminar(Integer id);
19+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package carmelo.spring.jpa.dao;
2+
3+
import carmelo.spring.jpa.model.Product;
4+
import java.sql.ResultSet;
5+
import java.sql.SQLException;
6+
import java.util.List;
7+
import javax.sql.DataSource;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.jdbc.core.JdbcTemplate;
10+
import org.springframework.jdbc.core.RowMapper;
11+
import org.springframework.stereotype.Repository;
12+
13+
@Repository("productDaoJdbc")
14+
public class ProductDaoImpl implements ProductDao {
15+
16+
private JdbcTemplate jdbcTemplate;
17+
18+
@Autowired
19+
public void setDataSource(DataSource dataSource) {
20+
this.jdbcTemplate = new JdbcTemplate(dataSource);
21+
}
22+
23+
@Override
24+
public List<Product> todos() {
25+
String sql = "select * from product";
26+
return this.jdbcTemplate.query(sql, new RowMapper<Product>() {
27+
@Override
28+
public Product mapRow(ResultSet rs, int i) throws SQLException {
29+
Product p = new Product();
30+
p.setId(rs.getInt("ID"));
31+
p.setName(rs.getString("NAME"));
32+
p.setPrice(rs.getDouble("PRICE"));
33+
return p;
34+
}
35+
});
36+
}
37+
38+
@Override
39+
public Integer cantidad() {
40+
String sql = "select count(*) from product";
41+
return this.jdbcTemplate.queryForObject(sql, Integer.class);
42+
}
43+
44+
@Override
45+
public Product buscar(Integer id) {
46+
String sql = "select * from product where ID = ?";
47+
return this.jdbcTemplate.queryForObject(sql, new ProductRowMapper(), id);
48+
}
49+
50+
@Override
51+
public void insertar(Product product) {
52+
String sql = "insert into product (ID, NAME, PRICE) values (?, ?, ?)";
53+
this.jdbcTemplate.update(sql,
54+
product.getId(),
55+
product.getName(),
56+
product.getPrice());
57+
}
58+
59+
@Override
60+
public void actualizar(Product product) {
61+
String sql = "update product set NAME = ?, PRICE = ? where ID = ?";
62+
this.jdbcTemplate.update(sql,
63+
product.getName(),
64+
product.getPrice(),
65+
product.getId());
66+
}
67+
68+
@Override
69+
public void eliminar(Integer id) {
70+
String sql = "delete from product where ID = ?";
71+
this.jdbcTemplate.update(sql, id);
72+
}
73+
74+
class ProductRowMapper implements RowMapper<Product> {
75+
76+
@Override
77+
public Product mapRow(ResultSet rs, int i) throws SQLException {
78+
Product p = new Product();
79+
p.setId(rs.getInt("ID"));
80+
p.setName(rs.getString("NAME"));
81+
p.setPrice(rs.getDouble("PRICE"));
82+
return p;
83+
}
84+
85+
}
86+
87+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package carmelo.spring.jpa.dao;
2+
3+
import carmelo.spring.jpa.model.Product;
4+
import java.util.List;
5+
import javax.persistence.EntityManager;
6+
import javax.persistence.PersistenceContext;
7+
import javax.persistence.Query;
8+
import org.springframework.stereotype.Repository;
9+
import org.springframework.transaction.annotation.Transactional;
10+
11+
@Repository("productDaoJpa")
12+
@Transactional
13+
public class ProductDaoJpaImpl implements ProductDao {
14+
15+
private EntityManager entityManager;
16+
17+
@PersistenceContext
18+
public void setEntityManager(EntityManager entityManager) {
19+
this.entityManager = entityManager;
20+
}
21+
22+
@Override
23+
public List<Product> todos() {
24+
String query = "from Product";
25+
return entityManager.createQuery(query).getResultList();
26+
}
27+
28+
@Override
29+
public Integer cantidad() {
30+
return entityManager
31+
.createQuery("select count(p) from Product p", Long.class)
32+
.getSingleResult().intValue();
33+
}
34+
35+
@Override
36+
public Product buscar(Integer id) {
37+
return entityManager.find(Product.class, id);
38+
}
39+
40+
@Override
41+
public void insertar(Product product) {
42+
entityManager.persist(product);
43+
}
44+
45+
@Override
46+
public void actualizar(Product product) {
47+
entityManager.merge(product);
48+
}
49+
50+
@Override
51+
public void eliminar(Integer id) {
52+
String jpql = "select p from Product p where p.id = :id";
53+
Query query = entityManager.createQuery(jpql);
54+
query.setParameter("id", id);
55+
Product p = (Product) query.getSingleResult();
56+
57+
if(p != null) {
58+
entityManager.remove(p);
59+
}
60+
}
61+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /