Categoría: Java
Último proyecto REST API con todo
Pasos para crear Hibernate
Crear un proyecto Maven
Escogemos maven-archetype-quickstart
En principio el de org.apache
Añadimos las dependencias de ‘Hibernate’ y ‘Mysql’. Os las pongo aquí.
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.32</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.15.Final</version> </dependency> </dependencies>
Después dentro de src/main creamos la carpeta ‘resources’: New folder
Dentro de resources creamos el archivo hibernate.cfg.xml, y dentro colocamos lo siguiente:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/sakila</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.show_sql">true</property> <mapping class="com.trifulcas.models.Actor" /> </session-factory> </hibernate-configuration>
Creamos un paquete com.trifulcas.models y dentro metemos nuestro POJO:
package com.trifulcas.models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name= "actor") public class Actor { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int actor_id; private String first_name; private String last_name; public Actor() { } /** * @return the actor_id */ public int getActor_id() { return actor_id; } /** * @param actor_id the actor_id to set */ public void setActor_id(int actor_id) { this.actor_id = actor_id; } /** * @return the first_name */ public String getFirst_name() { return first_name; } /** * @param first_name the first_name to set */ public void setFirst_name(String first_name) { this.first_name = first_name; } /** * @return the last_name */ public String getLast_name() { return last_name; } /** * @param last_name the last_name to set */ public void setLast_name(String last_name) { this.last_name = last_name; } @Override public String toString() { return "Actor id=" + actor_id + ",nombre=" + first_name+" "+last_name + "]"; } }
Y por último probaríamos que todo va bien, este código debería funcionar:
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build(); SessionFactory factory = meta.getSessionFactoryBuilder().build(); Session session = factory.openSession(); try { Actor penelope = session.get(Actor.class, 1); System.out.println(penelope.getFirst_name() + " " + penelope.getLast_name()); List<Actor> lista = session.createQuery("from Actor a where a.first_name like '%ar%' ").getResultList(); for (Actor a : lista) { System.out.println(a); } } catch (Exception ex) { System.out.println(ex); } factory.close(); session.close();
DAO comienzo
public class ActorDAO { private Connection con; public ActorDAO() { try { // Registrar el driver mysql Class.forName("com.mysql.cj.jdbc.Driver"); // Conectarme a la base de datos con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "root"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public ArrayList<Actor> getActorAll() { try { String sql="select * from actor"; PreparedStatement psmt=con.prepareStatement(sql); ResultSet res=psmt.executeQuery(); ArrayList<Actor> actores= new ArrayList<Actor>(); while (res.next()) { actores.add( new Actor(res.getInt("actor_id"), res.getString("first_name"), res.getString("last_name"))); } return actores; }catch(Exception ex) { ex.printStackTrace(); return null; } } public Actor getActor(int id) { try { String sql="select * from actor where actor_id=?"; PreparedStatement psmt=con.prepareStatement(sql); psmt.setInt(1, id); ResultSet res=psmt.executeQuery(); if (res.next()) { return new Actor(res.getInt("actor_id"), res.getString("first_name"), res.getString("last_name")); } else { return null; } }catch(Exception ex) { ex.printStackTrace(); return null; } } public boolean addActor(String first_name, String last_name) { try { String sql="insert into actor (first_name,last_name) values (?,?)"; PreparedStatement psmt=con.prepareStatement(sql); psmt.setString(1, first_name); psmt.setString(2, last_name); int res=psmt.executeUpdate(); return res==1; }catch(Exception ex) { ex.printStackTrace(); return false; } } public boolean addActor(Actor actor) { try { String sql="insert into actor (first_name,last_name) values (?,?)"; PreparedStatement psmt=con.prepareStatement(sql); psmt.setString(1, actor.getFirst_name()); psmt.setString(2, actor.getLast_name()); int res=psmt.executeUpdate(); return res==1; }catch(Exception ex) { ex.printStackTrace(); return false; } } }
public static void main(String[] args) { try { // El objeto DAO que me permite trabajar con la BD ActorDAO dao=new ActorDAO(); // Utilizar una de las propiedades: add for(int i=0;i<10000;i++) { dao.addActor("John"+i, "Travolta"); } //dao.addActor("John", "Travolta"); Actor eva=new Actor(0,"Eva","Wuig"); // dao.addActor(eva); System.out.println(dao.getActor(1)); System.out.println(dao.getActorAll()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Ejemplos JDBC
try { // Registrar el driver mysql Class.forName("com.mysql.cj.jdbc.Driver"); // Conectarme a la base de datos Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "root"); String nombre="Ana"; // Creo a partir de la conexión un comando Statement stmt = con.createStatement(); stmt.execute("insert into actor(first_name,last_name) values ('"+nombre+"','pi')"); // Los interrogantes son los parámetros PreparedStatement psmt=con.prepareStatement("insert into actor (first_name,last_name) values (?,?)"); psmt.setString(1, "Pep"); psmt.setString(2, "Pérez"); psmt.executeUpdate(); psmt.setString(1, "Pepa"); psmt.setString(2, "Pérez"); psmt.executeUpdate(); // Ejecuto un select y lo guardo en un resultset ResultSet rs = stmt.executeQuery("select * from actor where actor_id>20"); // Recorro el resultset y con get obtengo los valores while (rs.next()) { System.out.println(rs.getInt("actor_id") + " " + rs.getString(2) + " " + rs.getString(3)); } stmt.close(); con.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
Solucion Solid
package com.trifulcas.juegoPPTLSID; import java.util.Arrays; public class JuegoColores implements ILogica{ private String[] jugadas = { "verde","azul","amarillo","naranja","rojo" }; public JuegoColores() { } @Override public int comprobar(String jugada1, String jugada2) { int pos1 = Arrays.asList(jugadas).indexOf(jugada1.toLowerCase()); int pos2 = Arrays.asList(jugadas).indexOf(jugada2.toLowerCase()); if ((pos1 + 1) % jugadas.length == pos2) return 1; if ((pos2 + 1) % jugadas.length == pos1) return 2; return 0; } @Override public String[] validas() { return this.jugadas; } } package com.trifulcas.juegoPPTLSID; public interface IMostrar { void mostrar(String res); } package com.trifulcas.juegoPPTLSID; public class Juego { private Jugador jugador1; private Jugador jugador2; private ILogica _iLogica; private IMostrar _iMostrar; private String[] jugadas; public String[] getJugadas() { return jugadas; } public void setJugadas(String[] jugadas) { this.jugadas = jugadas; } public Jugador getJugador1() { return jugador1; } public void setJugador1(Jugador jugador1) { this.jugador1 = jugador1; } public Jugador getJugador2() { return jugador2; } public void setJugador2(Jugador jugador2) { this.jugador2 = jugador2; } public Juego(Jugador jugador1, Jugador jugador2, ILogica ilogica, IMostrar imostrar) { this.jugador1 = jugador1; this.jugador2 = jugador2; _iLogica = ilogica; jugadas = _iLogica.validas(); _iMostrar = imostrar; } public Juego(Jugador jugador1, Jugador jugador2, ILogica ilogica) { this(jugador1, jugador2, ilogica, new Consola()); } public String jugar() { jugador1.pedirJugada(jugadas); jugador2.pedirJugada(jugadas); _iMostrar.mostrar(jugador1.getNombre() + " elige " + jugador1.getJugada()); _iMostrar.mostrar(jugador2.getNombre() + " elige " + jugador2.getJugada()); int res = _iLogica.comprobar(jugador1.getJugada(), jugador2.getJugada()); String resultado="Empate"; if (res == 1) { resultado= jugador1.getNombre(); } if (res == 2) { resultado= jugador2.getNombre(); } _iMostrar.mostrar(resultado); return resultado; } } package com.trifulcas.juegoPPTLSID; public class Consola implements IMostrar { @Override public void mostrar(String res) { System.out.println(res); } } package com.trifulcas.juegoPPTLSID; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class Fichero implements IMostrar { @Override public void mostrar(String res) { Path path = Paths.get("resultado.txt"); try { if (!Files.exists(path)) Files.createFile(path); Files.writeString(path, res+"\r\n", StandardOpenOption.APPEND); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Soluciones ejercicios SOLID
package com.trifulcas.ejerciciosSolid; public class Article { private String Title; private String Content; public void setTitle(String title) { this.Title = title; } public void setContent(String content) { this.Content = content; } } package com.trifulcas.ejerciciosSolid; public class GenerateSummary { public String generateSummary(String content) { // Logic to generate a summary from the content return content.substring(0, 100) + "..."; // just a simple example } } package com.trifulcas.ejerciciosSolid; import com.trifulcas.juego.Enemigo; public class SaveToDatabase { // Cosas del tipo conexión a BD // etc... public void saveToDatabase(Article article) { // Logic to save the article to a database } public void saveToDatabase(Enemigo enemigo) { // Logic to save the article to a database } } package com.trifulcas.ejerciciosSolid; public abstract class ReportGenerator { public abstract void generateReport(String data); } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorPDF extends ReportGenerator { @Override public void generateReport(String data) { System.out.println("Aquí va el código de generar PDF"); } } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorCSV extends ReportGenerator { @Override public void generateReport(String data) { System.out.println("Código para generar CSV"); } } package com.trifulcas.ejerciciosSolid; public interface IReportGenerator { public void generateReport(String data); } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorXML implements IReportGenerator { @Override public void generateReport(String data) { System.out.println("Lógica para generar XML"); } } package com.trifulcas.ejerciciosSolid; public class ReportGeneratorID { IReportGenerator reportGenerator; public ReportGeneratorID(IReportGenerator reportGenerator) { this.reportGenerator = reportGenerator; } public void generateReport(String data) { reportGenerator.generateReport(data); } } package com.trifulcas.ejerciciosSolid; public class ProbarReports { public static void main(String[] args) { String datos="Hola que tal"; // Generar un PDF ReportGeneratorPDF rgp=new ReportGeneratorPDF(); rgp.generateReport(datos); // Generar un XML con ID ReportGeneratorXML rgx=new ReportGeneratorXML(); ReportGeneratorID rgid=new ReportGeneratorID(rgx); rgid.generateReport(datos); rgid=new ReportGeneratorID(rgx); rgid.generateReport(datos); } } package com.trifulcas.ejerciciosSolid; public interface IClean { void Clean(); } package com.trifulcas.ejerciciosSolid; public class Apartment implements IClean { @Override public void Clean() { System.out.println("Apartment cleaned."); } } package com.trifulcas.ejerciciosSolid; import java.util.Date; public interface IRoom { void Reserve(Date from, Date to); void CheckInventory(); } package com.trifulcas.ejerciciosSolid; public interface IInventory { void CheckInventory(); } package com.trifulcas.ejerciciosSolid; import java.util.Date; public interface IReserve { void Reserve(Date from, Date to); }
Piedra Papel Tijeras
https://github.com/juanpablofuentes/Java/tree/master/PiedraPapelTijera
Ejercicios Files
public class Alumno { // El public es un modificador de acceso // Quiere decir que cualquiera puede acceder al valor public String nombre; // Tenemos tres sabores de protección // public, protected y private private ArrayList<Integer> notas; // Los parámetros que queremos poner al crear la clase public Alumno(String nombre) { // Las cosas que queremos que se ejecuten // cuando creamos la clase // this.nombre es el nombre del objeto // nombre es el parámetro que le pasamos this.nombre = nombre; notas = new ArrayList<Integer>(); } public Alumno() { // Llamando a la sobrecarga del constructor this("anonimo"); } public int ponNota(int nota) { // Me aseguro de que mis notas están entre 0 10 if (nota > 0 && nota <= 10) { notas.add(nota); } return notas.size(); } public double media() { double total = 0; // Desde dentro de la clase si que puedo acceder for (int nota : notas) { total += nota; } return total / this.notas.size(); } }
public static void main(String[] args) { ArrayList<Alumno> alumnos=importar("archivo.txt"); System.out.println(estadoCarpeta("c:\\pepe")); ArrayList<String> nombres = new ArrayList<>(); Scanner sc = new Scanner(System.in); for (int i = 0; i < 5; i++) { System.out.println("Introduce nombre " + i); nombres.add(sc.next()); } Path path = Paths.get("nombres.txt"); try { Files.write(path, nombres, StandardOpenOption.CREATE); } catch (IOException e) { System.out.println(e.getMessage()); } } public static int estadoCarpeta(String ruta) { Path path = Paths.get(ruta); if (!Files.isDirectory(path)) { return -1; } try { List<Path> ficheros = Files.list(path).collect(Collectors.toList()); if (ficheros.size() == 0) { return 0; } // TODO: Crear un método aparte for (Path fichero : ficheros) { if (Files.isDirectory(fichero)) { return 2; } } return 1; } catch (IOException e) { System.out.println(e.getMessage()); return -1; } } public static ArrayList<Alumno> importar(String ruta) { List<String> contenido; // Leer fichero Path path = Paths.get(ruta); try { contenido = Files.readAllLines(path); } catch (Exception ex) { System.out.println(ex.getMessage()); return null; } // Crear arraylist /* * Nombre;nota Ana;5;6;7 Pep;3;3 Eva;5;5 */ ArrayList<Alumno> alumnos= new ArrayList<Alumno>(); for(int i=1;i<contenido.size();i++) { String[] elementos=contenido.get(i).split(";"); Alumno temp=new Alumno(elementos[0]); for(int j=1;j<elementos.length;j++) { temp.ponNota(Integer.parseInt(elementos[j])); } alumnos.add(temp); } return alumnos; }
public class Jugador { private String nombre; private ArrayList<Carta> mano; public Jugador(String nombre) { super(); this.nombre = nombre; mano = new ArrayList<>(); } protected String getNombre() { return nombre; } protected void setNombre(String nombre) { this.nombre = nombre; } protected ArrayList<Carta> getMano() { return mano; } protected void setMano(ArrayList<Carta> mano) { this.mano = mano; } protected void setMano(Carta carta) { this.mano.add(carta); } @Override public String toString() { return "Jugador [nombre=" + nombre + ", mano=" + mano + "]"; } public void logFichero(String ruta) { ArrayList<String> resultado = new ArrayList<>(); // Un arraylist con los datos que quiero escribir resultado.add("Nombre jugador: " + this.getNombre()); resultado.add("Cartas:"); for (Carta carta : mano) { resultado.add(carta.toString()); } // Escribir los datos try { Path path = Paths.get(ruta); if (!Files.exists(path)) { Files.createFile(path); } if (Files.isWritable(path)) { Files.write(path, resultado, StandardOpenOption.TRUNCATE_EXISTING); }else { // TODO: Lanzar excepción System.out.println("No se puede escribir"); } } catch (IOException e) { System.out.println(e.getMessage()); } } }
public static void main(String[] args) { Jugador ana=new Jugador("Ana Pi"); ana.setMano(new Espanyola("oros",12)); ana.setMano(new Espanyola("espadas",6)); ana.setMano(new Espanyola("copas",8)); ana.setMano(new Espanyola("oros",10)); ana.logFichero("cartas_ana.txt"); }
File, Files y Path
public static void main(String[] args) { File carpeta = new File("c:\\xampp"); exploreDirectory(carpeta); } public static void exploreDirectory(File directory) { // Obtiene una lista de los archivos y directorios contenidos en el directorio File[] files = directory.listFiles(); // Recorre cada archivo o directorio for (File file : files) { if (file.isFile()) { // Si es un archivo, imprime su nombre System.out.println(file.getName()); } else if (file.isDirectory()) { // Si es un directorio, llama recursivamente al método exploreDirectory(file); } } } Path path = Paths.get("C:/pepe/ejemplo.jpeg"); System.out.println(path.getFileName()); System.out.println(path.getName(0)); System.out.println(path.getParent()); System.out.println(path.getRoot()); path = Paths.get("archivo.txt"); System.out.println(path.getFileName()); System.out.println(path.getName(0)); System.out.println(path.getParent()); System.out.println(path.toAbsolutePath()); public static void main(String[] args) throws IOException { Path path = Paths.get("c:\\pepe\\archivo.txt"); String cadena="o muy bien\n"; Files.writeString(path, cadena,StandardOpenOption.APPEND ); ArrayList<String> texto=new ArrayList<>(Arrays.asList("adios","hola","que tal")); Files.write(path, texto, StandardCharsets.ISO_8859_1,StandardOpenOption.TRUNCATE_EXISTING); try { List<String> contenido = Files.readAllLines(path); for(String linea:contenido) { System.out.println(linea); } } catch (IOException e) { System.out.println(e); } } public static void main(String[] args) { Path path = Paths.get("c:\\pepe\\archivo2.txt"); ArrayList<String> texto=new ArrayList<>(Arrays.asList("adios","hola","qué tal")); try { Files.write(path, texto, StandardCharsets.ISO_8859_1,StandardOpenOption.CREATE_NEW); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { try { Path path = Paths.get("c:\\pepe\\archivo.txt"); List<String> contenido=Files.readAllLines(path,StandardCharsets.ISO_8859_1); for(String linea:contenido) { System.out.println(linea); } }catch(Exception ex) { System.out.println(ex.getMessage()); } }