-- Para cada país sus ciudades -- join me está diciendo que relaciono las dos tablas -- on me dirá mediante que campos están relacionados select country,city from country join city on country.country_id=city.country_id; select country,city from country co join city ci on co.country_id=ci.country_id; -- Solo vale para mysql y el campo se tiene que llamar igual select country,city from country join city using(country_id); select country,city,first_name,last_name from country join city on country.country_id=city.city_id join address on city.city_id=address.city_id join customer on address.address_id=customer.address_id; select name,title from category join film_category on category.category_id=film_category.category_id join film on film_category.film_id=film.film_id; -- left join nos dice que devolvamos los valores de la tabla de la izquierda -- Aunque no tengamos valores relacionados select name,title from category left join film_category on category.category_id=film_category.category_id left join film on film_category.film_id=film.film_id; -- right join nos dice que devolvamos los valores de la tabla de la derecha -- Aunque no tengamos valores relacionados select name,title from category right join film_category on category.category_id=film_category.category_id right join film on film_category.film_id=film.film_id
Autor: Juan Pablo Fuentes
Sakila esquema
Insert de revistas
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Nature’, ‘1234-5678’, 1, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Science’, ‘5678-1234’, 2, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘The New England Journal of Medicine’, ‘8765-4321’, 3, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘The Lancet’, ‘4321-8765’, 4, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Cell’, ‘9876-5432’, 5, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Nature Reviews Immunology’, ‘5432-9876’, 6, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Journal of the American Medical Association’, ‘2345-6789’, 7, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘Nature Genetics’, ‘6789-2345’, 8, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘The Astrophysical Journal’, ‘3456-7890’, 9, 2023);
INSERT INTO Revistas (Titulo, ISSN, Numero, Anyo) VALUES (‘IEEE Transactions on Neural Networks and Learning Systems’, ‘7890-3456’, 10, 2023);
Catálogo revistas
DROP TABLE IF EXISTS `revista` ;
CREATE TABLE IF NOT EXISTS `revista` (
`idrevista` INT NOT NULL AUTO_INCREMENT,
`titulo` VARCHAR(100) NOT NULL,
`issn` CHAR(9) NOT NULL,
`numero` INT NOT NULL,
`anyo` YEAR NOT NULL,
PRIMARY KEY (`idrevista`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `articulo` ;
CREATE TABLE IF NOT EXISTS `articulo` (
`idarticulo` INT NOT NULL AUTO_INCREMENT,
`titulo` VARCHAR(100) NOT NULL,
`inicio` INT NOT NULL,
`final` INT NOT NULL,
`idrevista` INT NOT NULL,
PRIMARY KEY (`idarticulo`),
CONSTRAINT `idrevista`
FOREIGN KEY (`idrevista`)
REFERENCES `revista` (`idrevista`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
CREATE INDEX `idrevista_idx` ON `articulo` (`idrevista` ASC) VISIBLE;
DROP TABLE IF EXISTS `autor` ;
CREATE TABLE IF NOT EXISTS `autor` (
`idautor` INT NOT NULL AUTO_INCREMENT,
`nombre` VARCHAR(100) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`pais` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idautor`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `articulo_autor` ;
CREATE TABLE IF NOT EXISTS `articulo_autor` (
`idarticulo_autor` INT NOT NULL AUTO_INCREMENT,
`idautor` INT NOT NULL,
`idarticulo` INT NOT NULL,
`posicion` INT NOT NULL,
PRIMARY KEY (`idarticulo_autor`),
CONSTRAINT `idarticulo`
FOREIGN KEY (`idarticulo`)
REFERENCES `articulo` (`idarticulo`),
CONSTRAINT `idautor`
FOREIGN KEY (`idautor`)
REFERENCES `autor` (`idautor`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
CREATE INDEX `idarticulo_idx` ON `articulo_autor` (`idarticulo` ASC) VISIBLE;
CREATE INDEX `idautor_idx` ON `articulo_autor` (`idautor` ASC) VISIBLE;
Modelos ER
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()); } }